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

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

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

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

Is this possible with Linq?

+4
source share
3 answers

LINQ is not really intended for mutation; however, you can use something like Select overload, which includes an index. But honestly? Just loop and hold the counter. It is much easier to understand, and this is important.

 int position = 0; foreach(var obj in collection) { position++; obj.Name = "Effect " + position.ToString(); } 
+8
source
 var n = 0; collection.ForEach(x=>x.Name = "Effect {0}".FormatWith(++n)); 

These are the simple extension methods that I returned in 3.5:

 public static void ForEach<T>(this IEnumerable<T> collection, Action<T> lambda) { foreach(var element in collection) lambda(element); } public static string FormatWith(this string base, params object[] args) { return String.Format(base, args); } 
+1
source

This is not the best solution for LINQ, but :

 class Program { private class Effect { public string Name { get; set; } } static void Main(string[] args) { List<Effect> list = new List<Effect> {new Effect(), new Effect(), new Effect()}; var newElements = list.Select((element, index) => { element.Name = "Effect " + index.ToString(); return element; }); foreach (var effect in newElements) { Console.WriteLine(effect.Name); } } } 

Outputs:

Effect 0

Effect 1

Effect 2

+1
source

Source: https://habr.com/ru/post/1338339/


All Articles