Number of elements of a linq projection element

Let's pretend that:

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 to set the value of this counter? Or can I continue the iteration aafter?

+5
source share
2 answers

Use Select overload , which will give you the current index based on element 0.

.Select((item, index) => new MyType
            { 
                counter = index + 1,
                a = item.Something
+8
source

Just write the variable:

int index = 1;

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

The counter will increase as each iteration is called.

+3
source

All Articles