动态 Linq 排序不适用于 ArrayList
Dynamic Linq Sort not working for ArrayList
我正在尝试执行以下操作
string orderedBy = "item.length";
var sorted = from PPart item in partList
orderby orderedBy
select item;
其中 partList 是包含 PPart 类型对象的数组列表。上面的语句不是对 arrayList 进行排序。
如果我直接在 linq 查询中写 item.length,如下所示,那么列表正在排序
var sorted = from PPart item in partList
orderby item.length
select item;
如何使动态 linq 与后期绑定一起工作
您可以使用表达式树来做到这一点,例如:
public static Func<PPart, IComparable> GetOrderByPropertyExpression(string propertyName)
{
ParameterExpression parameter = Expression.Parameter(typeof (PPart));
PropertyInfo baseProperty = typeof (PPart).GetProperty(propertyName);
Expression memberExpression = Expression.Property(parameter, baseProperty);
return
Expression.Lambda<Func<PPart, IComparable>>(Expression.TypeAs(memberExpression, typeof (IComparable)),
parameter).Compile();
}
并按如下方式使用它:
IOrderedEnumerable<PPart> ordered = partList.OrderBy(PPart.GetOrderByPropertyExpression("length"));
没有提供错误检查,只是一个概念。
我正在尝试执行以下操作
string orderedBy = "item.length";
var sorted = from PPart item in partList
orderby orderedBy
select item;
其中 partList 是包含 PPart 类型对象的数组列表。上面的语句不是对 arrayList 进行排序。
如果我直接在 linq 查询中写 item.length,如下所示,那么列表正在排序
var sorted = from PPart item in partList
orderby item.length
select item;
如何使动态 linq 与后期绑定一起工作
您可以使用表达式树来做到这一点,例如:
public static Func<PPart, IComparable> GetOrderByPropertyExpression(string propertyName)
{
ParameterExpression parameter = Expression.Parameter(typeof (PPart));
PropertyInfo baseProperty = typeof (PPart).GetProperty(propertyName);
Expression memberExpression = Expression.Property(parameter, baseProperty);
return
Expression.Lambda<Func<PPart, IComparable>>(Expression.TypeAs(memberExpression, typeof (IComparable)),
parameter).Compile();
}
并按如下方式使用它:
IOrderedEnumerable<PPart> ordered = partList.OrderBy(PPart.GetOrderByPropertyExpression("length"));
没有提供错误检查,只是一个概念。