使用LINQ将增量属性按组添加到IEnumerable [英] Add incremented property to IEnumerable by group using LINQ
本文介绍了使用LINQ将增量属性按组添加到IEnumerable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为简化方案,假设我们有一个具有FirstName和LastName属性的人员列表.
To simplify the scenario, let's say we have a list of People with FirstName and LastName properties.
我们的数据如下:
Bob Smith
Jane Smith
Todd Grover
Larry Lewis
Jill Lewis
Frank Lewis
第一步是添加一个Integer属性,该属性将为每个项目递增:
The first step would be to add an Integer property that gets incremented for each item:
Bob Smith 1
Jane Smith 2
Todd Grover 3
Larry Lewis 4
Jill Lewis 5
Frank Lewis 6
理想情况下,我想为每个新组重置计数器以实现此目的:
Ideally, I'd like to reset the counter for every new group to achieve this:
Bob Smith 1
Jane Smith 2
Todd Grover 1
Larry Lewis 1
Jill Lewis 2
Frank Lewis 3
也许LINQ不适合.看起来LINQ应该可以优雅地做到这一点.
Maybe LINQ isn't appropriate. It just seems like LINQ should be able to do this elegantly.
推荐答案
如果您只希望计数器随每个项目递增:
If you just want a counter that increments with each item:
var query = people
.Select((x, i) => new { x.FirstName, x.LastName, Index = i + 1 });
或者如果要重置每个组的计数器,则按LastName
分组:
Or if you want to reset the counter for each group, grouped by LastName
:
var query = people
.GroupBy(x => x.LastName)
.Select
(
x => x.Select((y, i) => new { y.FirstName, y.LastName, Index = i + 1 })
)
.SelectMany(x => x);
并快速显示查询结果:
foreach (var item in query)
{
Console.WriteLine(item.FirstName + "\t" + item.LastName + "\t" + item.Index);
}
这篇关于使用LINQ将增量属性按组添加到IEnumerable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文