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

标签 c# .net linq grouping

我想实现类似于 this 的东西.但我不知道我可以以何种方式使用该解决方案。

我的实体有这些属性

CustomerName
Date
SortOrder

我有这个实体的完整列表。我想要做的是,将 List<> 中具有连续 SortOrder 和相同 Date 以及相同 CustomerName

的所有项目分组

示例输入

  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 解决方案也足够了。

最佳答案

这是一个可能的 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))
        )

关于c# - 使用 LINQ 根据条件将集合拆分为多个部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4023282/

相关文章:

C# 简单的 2d 游戏 - 制作基本的游戏循环

.net - 免费的 NHibernate 辅助工具?

.net - 带有 wsHttpBinding 且没有 Windows 安全性的 WCF session

c# - 使用 Lambda 的内部连接 ​​(LINQ)

c# - WPF如何连接MYSQL?

c# - 在 c#.net 中设置饼图中的颜色

c# - 是否可以将 System.Text.Encoding 类从 JSON 反序列化为 C# 中的代码?

c# - WCF Web 服务 - 同一台服务器上的多跃点模拟

c# - linq - 在 Any() 调用中使用来自父对象的属性

c# - LINQ 能够过滤关联,但直接引用时返回 0 个结果