代码之家  ›  专栏  ›  技术社区  ›  IsmailS

根据使用LINQ的条件将集合拆分为多个部分?

  •  5
  • IsmailS  · 技术社区  · 14 年前

    我想达到类似的目标 this . 但我不知道我能用什么方法来解决这个问题。

    我的实体具有这些属性

    CustomerName
    Date
    SortOrder
    

    我有这个实体的完整列表。我要做的是,将列表中所有连续的项目分组 排序顺序 同样的 日期 同样的 客户名称

    示例输入

      var inv = new List<Invoice>(){
        new Invoice(){ CustomerName = "Abc" ,Date = DateTime.Today, SortOrder = 0},
        new Invoice(){ CustomerName = "Abc" ,Date = DateTime.Today, SortOrder = 1},
        new Invoice(){ CustomerName = "Abc" ,Date = DateTime.Today, SortOrder = 2},
        new Invoice(){ CustomerName = "xyz" ,Date = DateTime.Today.Subtract(TimeSpan.FromDays(1)), SortOrder = 3},
        new Invoice(){ CustomerName = "xyz" ,Date = DateTime.Today.Subtract(TimeSpan.FromDays(1)), SortOrder = 4},
        new Invoice(){ CustomerName = "Abc" ,Date = DateTime.Today, SortOrder = 5},
        new Invoice(){ CustomerName = "Abc" ,Date = DateTime.Today, SortOrder = 6}
      };
    

    示例输出

      var invGrouped = new List<List<Invoice>>
       {
         new List<Invoice>
           {
             new Invoice {CustomerName = "Abc", Date = DateTime.Today, SortOrder = 0},
             new Invoice {CustomerName = "Abc", Date = DateTime.Today, SortOrder = 1},
             new Invoice {CustomerName = "Abc", Date = DateTime.Today, SortOrder = 2}
           },
         new List<Invoice>
           {
             new Invoice {CustomerName = "xyz", Date = DateTime.Today.Subtract(TimeSpan.FromDays(1)), SortOrder = 3},
             new Invoice {CustomerName = "xyz", Date = DateTime.Today.Subtract(TimeSpan.FromDays(1)), SortOrder = 4}
           },
         new List<Invoice>
           {
             new Invoice {CustomerName = "Abc", Date = DateTime.Today, SortOrder = 5},
             new Invoice {CustomerName = "Abc", Date = DateTime.Today, SortOrder = 6}
    
           }
       };
    

    更新
    非LINQ解决方案也足够了。

    1 回复  |  直到 12 年前
        1
  •  5
  •   diceguyd30    14 年前

    下面是一个可能的LINQ答案,尽管我确信存在一个更有效的答案:

        inv
            .GroupBy(x => new { CustomerName = x.CustomerName, Date = x.Date })
            .SelectMany(x => x
                                .OrderBy(y => y.SortOrder)
                                .Select((y,i) => new { Value = y, Sort = y.SortOrder - i })
                                .GroupBy(y => y.Sort)
                                .Select(y => y.Select(z => z.Value))
            )