I have a collection with objects of different types, each of them inheriting from a class named Component. I then want to modify the collections by my needs nicely, with use of kind of declarative and fluent syntax.
For each item type in the collection i need to do other actions so i came up with the following LINQ style extension method:
public static IEnumerable<T> DoWith<T, T2>(this IEnumerable<T> items, Action<T2> action) { foreach (var item in items) { if (item is T2 t) action(t); yield return item; } } So I call it like that:
myComponents .DoWith((ConstructionSiteComponent c) => c.structureTemplateKey = "newTemplate") .DoWith((EntityNameComponent c) => c.Name = $"Construction site for {origName}"); But surprise, nothing happens since the enumerable is not enumerated. Sure I can fix this by either actually using a foreach statement of even calling .ToArray() which internally enumerates the collection, but this all does not feel right.
I would also imagine instead of modifying items to actually replace them, but i guess the problem would also apply then also, right?
ListhasForEachmethod and it should be enough. Anyway, you can create extension method forListor other collection interface, returning the same instance and it will be ok,