[英]Auto-incrementing a generic list using LINQ in C#
Is there a good way to provide an "auto-increment" style index column (from 1..x) when projecting items using LINQ? 使用LINQ投影项目时,有没有一种好的方法来提供“自动递增”样式索引列(从1..x开始)?
As a basic example, I'm looking for the index column below to go from 1 to the number of items in list. 作为一个基本示例,我正在寻找下面的索引列,其范围从1到列表中的项目数。
var items = from s1 in list
select new BrowsingSessionItemModel { Id = s1.Id, Index = 0 };
Iterating through the list would be the easy option but I was wondering if there was a better way to do this? 遍历列表是一个简单的选择,但是我想知道是否有更好的方法可以做到这一点?
You can use the overload of Select
which takes the provides the index to the projection as well: 您可以使用
Select
的重载,该重载也为投影提供索引:
var items = list.Select((value, index) => new BrowsingSessionItemModel {
Id = value.Id,
Index = index
});
Note that there is no query expression support for this overload. 请注意,此重载不支持查询表达式。 If you're actually fetching the values from a database (it's not clear whether
list
is really a List<T>
) you should probably make sure you have an appropriate ordering, as otherwise the results are somewhat arbitrary. 如果您实际上是从数据库中获取值(尚不清楚
list
是否真的是List<T>
),则可能应确保您具有适当的顺序,否则结果将有些随意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.