LINQ的处理可变数量排序依据的 [英] Linq handling variable number of OrderBy

查看:108
本文介绍了LINQ的处理可变数量排序依据的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要支持一个LINQ(到实体)语句可变数量排序依据的条款。也就是说,我的功能将接受在其上的数据应顺序属性的列表。属性可以兼得升序或降序排序。什么是处理构建LINQ查询的最好方法是什么?

I need to support a variable number of Orderby terms in a Linq (to Entity) statement. That is, my function will accept a list of properties on which the data should be order. The properties can have both ascending or descending sorts. What is the best way to handle constructing the Linq query?

谢谢!

推荐答案

您应该能够做到这些方针的东西:

You should be able to do something along these lines:

public IEnumerable<MyType> DoSomething(params Expression<Func<MyType,object>>[] properties)
 {
     var query = // create LINQ query that returns IQueryable<MyType>
     query = query.OrderBy(properties.First());

     foreach (var property in properties.Skip(1))
     {
         query = query.ThenBy(property);
     }
 }

 …

 var results = DoSomething(() => x.Age, () => x.Height, () => x.LastName);

您就需要处理,其中被指定少于2性能的情况下。

You'd need to handle the case where fewer than 2 properties are specified.

这篇关于LINQ的处理可变数量排序依据的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆