【问题标题】:Use LINQ for arbitrary sorting使用 LINQ 进行任意排序
【发布时间】:2009-10-07 22:02:53
【问题描述】:

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

【问题讨论】:

    标签: linq sorting entities


    【解决方案1】:

    当然。您可以将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?
    });
    

    【讨论】:

      猜你喜欢
      • 2018-07-26
      • 2020-07-08
      • 2021-06-30
      • 2012-01-28
      • 2010-12-31
      • 2017-02-22
      • 1970-01-01
      • 1970-01-01
      • 2016-11-10
      相关资源
      最近更新 更多