繁体   English   中英

使用LINQ对IEnumerable进行排序

[英]Sorting IEnumerable using LINQ

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

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

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

我为orderBy参数传递了一个有效的p.property,为sortOrder参数传递了“ascending”或“descending”

如果我不能像这样以有限的方式“动态化”我的LINQ,除了一个丑陋的Switch语句之外还有什么替代方案呢?

非常感谢你的时间。

我认为你结合了查询符号和点符号。 为此,请尝试坚持使用点符号:

sortedPremiseList = premiseList
           .OrderBy(p => string.Format("{0} {1}", p.orderBy, p.sortOrder));

我想我明白你在这里要求的是什么。 您想从字符串参数构造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表达式在编译时转换为代码,并且在传递它之前不会计算传递它的字符串。

我认为你需要在string.Format()调用中引用p ,如下所示:

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

这对我有用:

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);
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM