c# - Linq to Objects 按任意数量的参数排序

标签 c# linq dynamic sql-order-by func

我有一个 Func 列表定义了一个顺序:

var ordering = new List<Func<Person, IComparable>> 
                 { x => x.Surname, x => x.FirstName };

我可以用类似...的方式排序结果

people = people.OrderBy(ordering[0]).ThenBy(ordering[1]);

当列表可以包含任意数量的顺序排序时,我正在尝试弄清楚如何执行上述操作。可能吗?

最佳答案

people = people.OrderBy(ordering[0]).ThenBy(ordering[1]).ThenBy(ordering[2]);

相同
var orderedPeople = people.OrderBy(ordering[0]);
orderedPeople = orderedPeople.ThenBy(ordering[1]);
orderedPeople = orderedPeople.ThenBy(ordering[2]);
people = orderedPeople;

所以你只需像这样写一个循环:

if (ordering.Count != 0)
{
    var orderedPeople = people.OrderBy(ordering[0]);
    for (int i = 1; i < ordering.Count; i++)
    {
        orderedPeople = orderedPeople.ThenBy(ordering[i]);
    }
    people = orderedPeople;
}

关于c# - Linq to Objects 按任意数量的参数排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7322983/

相关文章:

c++ - C++中插件的“Best fit”动态类型匹配

c# - 从字符串生成子字符串的组合

c# - 在服务器端同时进行排序和分页的 DocumentDb 查询,可能吗?

c# - 使用 MvvmLight 和 Xamarin.iOS 将属性绑定(bind)到 ViewModel

c# - 使用 LINQ to SQL 左连接

c# - 如何使用where条件

c# - 如何通过输入和输出值估计数学函数?

c# - 在 codedom 中使用动态对象创建 LINQ 查询

c# - 我如何使用 LINQ 过滤掉以各种子字符串开头的字符串?

javascript - prettyPhoto 和 Ajax 加载的内容