C# 我可以和LINQ一起把我的报告分成小组吗?
我有以下报告:C# 我可以和LINQ一起把我的报告分成小组吗?,c#,linq,grouping,C#,Linq,Grouping,我有以下报告: var report = _repository.GetAll( .OrderBy(item => item.RowKey.Substring(0, 4)) .Select((t, index) => new Question.Grid() { RowKey = t.RowKey, Row = index + 1, ShortTitle = t.ShortTitle } 这给了我: RowKey Order
var report = _repository.GetAll(
.OrderBy(item => item.RowKey.Substring(0, 4))
.Select((t, index) => new Question.Grid()
{
RowKey = t.RowKey,
Row = index + 1,
ShortTitle = t.ShortTitle
}
这给了我:
RowKey Order Title
0000 1 Title 1
0001 2 Title 2
0010 3 Title 3
0010 4 Title 4
0100 5 Title 5
0101 6 Title 6
0101 7 Title 7
我需要做的是做一份两列的报告,这将给我关于
a) When digits 1-2 of the row key change
b) When digits 3-4 of the row key change
像这样:
Key Count
00 4
0001 1
0010 3
01 3
0100 1
0101 2
或者如果这更容易:
Key Count
0000 4
0001 1
0010 2
0100 2
0100 1
0101 2
这是我可以用LINQ做的吗?类似的事情
var groups = _repository.GetAll()
.GroupBy(x => x.RowKey.Substring(0, 2))
.Select(x => new
{
RowKey = x.Key, // + "00"
Count = x.Count(),
SubItems = x
.GroupBy(y => y.RowKey.Substring(0, 4))
.Select(z => new
{
RowKey = z.Key,
Count = z.Count()
})
});
foreach(var outerGroup in groups)
{
Console.WriteLine(outerGroup.RowKey + " " + outerGroup.Count);
foreach(var innerGroup in outerGroup.SubItems)
{
Console.WriteLine(innerGroup.RowKey + " " + innerGroup.Count);
}
}