使用LINQ对IEnumerable进行排序

4

在SO上有很多类似的问题,但我没有看到一个适合我的情况...

我想知道为什么这样不能对Premise对象的IEnumerable进行排序:

sortedPremiseList = from p in premiseList
                 orderby (string.Format("{0} {1}", orderBy, sortOrder))
                  select p;

我正在为orderBy参数传递有效的p.property,并且对于sortOrder参数传递“ascending”或“descending”。
如果我不能以这种有限的方式“动态化”我的LINQ,除了一个大而丑陋的Switch语句之外,还有什么替代方案吗?
非常感谢您的时间。

string.Format的参数不应该是p.OrderBy和p.sortOrder吗? - Marcelo Zabani
2
Marc Gravell在这个答案中为IEnumerable提供了动态LINQ OrderBy。 - hypermush
似乎对我来说最好的解决方案是使用hypermush建议的Marc代码。 - theog
4个回答

2
我认为您正在混合使用查询符号和点符号。为此,请尝试仅使用点符号:
sortedPremiseList = premiseList
           .OrderBy(p => string.Format("{0} {1}", p.orderBy, p.sortOrder));

1

我认为你需要在string.Format()调用中引用p,像这样:

sortedPremiseList = from p in premiseList
    orderby (string.Format("{0} {1}", p.orderBy, p.sortOrder))
    select p;

1

我想我明白你在这里要求什么。你想从字符串参数构建LINQ查询。

好的,我喜欢挑战。

IComparable GetPropValue( object src, string propName )
{
  return (IComparable)src.GetType( ).GetProperty( propName ).GetValue( src, null );
}

IEnumerable<Premise> SortMyPremises(IEnumerable<Premise> premises, string propertyName, string ascendingOrDescending) 
{
  return ascendingOrDescending = "ascending" 
    ? premises.OrderBy(p => GetPropValue(p, propertyName)) 
    : premises.OrderByDescending(p => GetPropValue(p, propertyName));
}

你写的方式不起作用的原因是,LINQ表达式在编译时被转换为代码,而你传递的字符串直到运行时才被评估。

0

这对我有用:

public static IEnumerable<TEntity> OrderBy<TEntity>(this IEnumerable<TEntity> source, string orderByProperty,
                            bool desc)
        {
            string command = desc ? "OrderByDescending" : "OrderBy";
            var type = typeof(TEntity);
            var property = type.GetProperty(orderByProperty);
            var parameter = Expression.Parameter(type, "p");
            var propertyAccess = Expression.MakeMemberAccess(parameter, property);
            var orderByExpression = Expression.Lambda(propertyAccess, parameter);
            var resultExpression = Expression.Call(typeof(Queryable), command, new Type[] { type, property.PropertyType },
                                          source.AsQueryable().Expression, Expression.Quote(orderByExpression));
            return source.AsQueryable().Provider.CreateQuery<TEntity>(resultExpression);
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接