问题描述:

Is there a good way to provide an "auto-increment" style index column (from 1..x) when projecting items using LINQ?

As a basic example, I'm looking for the index column below to go from 1 to the number of items in list.

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't do this with LINQ expressions. You could use the following .Select extension method though:

var items = list.Select((x, index) => new BrowsingSessionItemModel { 
    Id = x.Id, 
    Index = index 
});
网友答案:

You can use the overload of Select which takes the provides the index to the projection as well:

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.

相关阅读:
Top