0

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?

2
  • 1
    There are no best practices. LINQ is immutable by default. What you are trying to do is multiple enumerations of single Enumerable, which is bad. List has ForEach method and it should be enough. Anyway, you can create extension method for List or other collection interface, returning the same instance and it will be ok, Commented Dec 22, 2023 at 10:24
  • @SvyatoslavDanyliv: Nothing is enumerated here, that was my point.. My DoWith method works like the Where clause, which also only "virtually" enumerates the collection. A Linq expression with multiple where clauses is also not enumerated multiple times. Commented Dec 22, 2023 at 20:45

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.