Skip to main content

Linq ForEach with index

Once you start using Linq in .NET you never go back...

Even simple tasks as looping a list of items you still use Linq. But what happens when you actually need the index variable you get for free when using for-loop?

Assume a list of objects:


var values = new List<int>() { 2, 3, 4, 0x100, 74, 0xFFFF, 0x0F0F };

To iterate the list and having an index do the following:


values.Select((x, i) => new
{
    item = x,
    index = i
})
.ToList()
.ForEach(obj =>
{
    int value = obj.item;
    int valueIndex = obj.index;
});

See also my answer on Stack Overflow.

Comments