Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linq projection element count

Tags:

c#

linq

Suppose:

var a = SomeCollection.OrderBy(...)
              .Select(f => new MyType
                               {
                                  counter = ? //I want counter value, so what first
                                              //object have counter=1, second counter=2 
                                              //and so on
                                  a=f.sometthing,
                                  ...
                                });

How do I set this counter value? Or do I fave to iterate a afterwards?

like image 719
ren Avatar asked Aug 25 '11 17:08

ren


2 Answers

Use the overload of Select that gives you the current element's 0-based index.

.Select((item, index) => new MyType
            { 
                counter = index + 1,
                a = item.Something
like image 177
Anthony Pegram Avatar answered Nov 20 '22 17:11

Anthony Pegram


Simply capture a variable:

int index = 1;

var a = SomeCollection.OrderBy(...)
        .Select(x => new MyType { counter = index++; });

The counter will increment as each iteration is called.

like image 3
Tejs Avatar answered Nov 20 '22 15:11

Tejs