我希望实现与this类似的功能。但我不知道我能以何种方式使用该解决方案。
我的实体有这些属性
CustomerName
Date
SortOrder
我已经完整列出了这个实体。我想要做的是,将列表中的所有项目分组<>它具有连续的 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解决方案也足够了。
答案 0 :(得分:5)
这是一个可能的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))
)