通常,当提供用户指定的排序顺序,并使用LINQ进行排序时,我最终会遇到这样一个丑陋的场景:
public static IEnumerable<ConfirmationItemViewModel> SortAscending(IEnumerable<ConfirmationItemViewModel> confirmations, string sortProperty)
{
switch (sortProperty)
{
case "CreatedOn":
confirmations = confirmations.OrderBy(i => i.CreatedOn).ToList();
break;
case "PaymentId":
confirmations = confirmations.OrderBy(i => i.PaymentId).ToList();
break;
default:
confirmations = confirmations.OrderBy(i => i.PaymentId).ThenBy(i => i.CreatedOn).ToList();
break;
}
return confirmations;
}OrderBy方法接受Func<TSource, TKey>类型的函数委托,我认为它用于从被排序的集合中的每个项中获取排序属性的值。我想编写一个使用属性名称而不是委托的方法,并返回返回属性值的委托,如果这一半解释了我的意思。
希望我对它进行编码的尝试,这是不起作用的,将解释更多。鉴于我对表达方式和代表的理解有限,这是我所能得到的最接近的结果:
public static Func<TObject, TKey> BuildKeySelector<TObject, TKey>(TObject source, string propertyName)
{
return obj =>
{
var prop = source.GetType().GetProperty(propertyName, typeof(TKey));
return (TKey) prop.GetValue(obj);
};
}
static void Main(string[] args)
{
// Sort a list of Person objects by their Name property.
var peeps = new List<Person>();
var rank = peeps.OrderBy(BuildKeySelector(<something>, "Name"));
}发布于 2016-01-17 15:11:30
您不需要TObject object作为参数。如果您看到只使用source来获取类型,这一点就变得很清楚了。
以下是您可以这样做的方法:
public static Func<TObject, TKey> BuildKeySelector<TObject, TKey>(string propertyName)
{
return obj =>
{
var prop = typeof(TObject).GetProperty(propertyName, typeof(TKey));
return (TKey) prop.GetValue(obj);
};
}但是,这并不是很有效,因为您的函数(从BuildKeySelector方法返回的委托)每次都会使用反射来获取属性值。更好的方法是构建表达式(可以缓存)并将表达式编译为委托。
https://stackoverflow.com/questions/34839717
复制相似问题