Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

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?

like image 664
Nick Avatar asked Oct 14 '11 08:10

Nick


2 Answers

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 
});
like image 114
Darin Dimitrov Avatar answered Oct 21 '22 10:10

Darin Dimitrov


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.

like image 38
Jon Skeet Avatar answered Oct 21 '22 12:10

Jon Skeet