linq - 使用 LINQ 进行任意排序

标签 linq sorting entities

假设我们有一个具有属性 att1 和 att2 的实体,其中 att1 的值可以是 a、b、c,att2 的值可以是 1、2、3。是否可以使用 LINQ,以便我们可以通过应用任意排序规则对集合中的项目进行排序,而无需实现 IComparable。我面临一个问题,即业务要求在某些屏幕上集合中的项目以一种方式排序,而在其他屏幕上以其他方式排序。例如,规则可以声明需要对项目进行排序,以便首先列出“b”,然后是“a”,然后是“c”,并且在每个组中,首先是“3”,然后是“1”,然后是“2”。

最佳答案

当然。您可以将 OrderBy 与一个谓词一起使用,该谓词或多或少地返回您喜欢的任意类型的任意“排序顺序”。例如:

objectsWithAttributes.OrderBy(x =>
{
    // implement your "rules" here -- anything goes as long as you return
    // something that implements IComparable in the end.  this code will sort
    // the enumerable in the order 'a', 'c', 'b'

    if (x.Attribute== 'a')
        return 0;
    else if (x.Attribute== 'c')
        return 1;
    else if (x.Attribute== 'b')
        return 2;
}).ThenBy(x =>
{
    // implement another rule here?
});

关于linq - 使用 LINQ 进行任意排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/921107/

相关文章:

c# - 将 IEnumerable<T> 拆分为固定大小的 block (返回 IEnumerable<IEnumerable<T>> ,其中内部序列具有固定长度)

c# - order by then count 和 select Max by group,性能问题

c# - 复杂的 LINQ 'Any' 查询

MySQL按 parent 和 child 排序

C++:两个指向相同结构的指针 vector ,每个 vector 的排序不同

c# - 从列表的自定义列中选择一个元素

c# - LINQ 知道如何优化 "queries"吗?

javascript - Javascript 数组排序是异步的吗?

java - POJO 作为 mongodb 中的文档

java - 如何强制 javax xslt 转换器使用 utf-8 而不是 html 实体对国家字符进行编码?