Nick
Nick

Reputation: 5892

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?

Upvotes: 8

Views: 13126

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1502206

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.

Upvotes: 9

Darin Dimitrov
Darin Dimitrov

Reputation: 1039130

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 
});

Upvotes: 15

Related Questions