我想实现类似于 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/