Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rename data using Linq based on the location of elements?

If I have an Effect collection that's IEnumerable<Effect>, how do I set their .Name property based on their location in the collection?

So in the end, I just want them to be renamed starting from 1 to n.

<inside the collection>
effectInstance1.Name = Effect 1;
effectInstance2.Name = Effect 2;
effectInstance3.Name = Effect 3;
...

Is this possible with Linq?

like image 762
Joan Venge Avatar asked Dec 29 '22 01:12

Joan Venge


1 Answers

LINQ isn't really intended for mutation anyway; however, you could use something like the Select overload that includes the index. But to be honest? Just loop and keep a counter. Much easier to understand, and that matters.

int position = 0;
foreach(var obj in collection) {
    position++;
    obj.Name = "Effect " + position.ToString();
}
like image 78
Marc Gravell Avatar answered Feb 05 '23 13:02

Marc Gravell