Acrotygma
Acrotygma

Reputation: 2569

List<T>.ForEach() set property, return IEnumerable?

The LINQ extension List.ForEach() doesn't return anything (void), but I would like to assign a property value to all objects in a list and then return some of them as IEnumerable.

e.g.

return myCollection
     .ForEach(x => x.ToBeDetermined = determine(x))
     .Where(x => x.ToBeTermined == true);

Upvotes: 0

Views: 2969

Answers (5)

Adi Lester
Adi Lester

Reputation: 25211

As an extension method, also making it more readable than other solutions (and also reusable):

public static IEnumerable<T> ForEachEx<T>(this IEnumerable<T> source, Action<T> action)
{
    foreach (T item in source)
    {
        action(item);
    }
    return source;
}

Which makes the usage exactly as you had it in your original question:

return myCollection.ForEachEx(x => x.ToBeDetermined = determine(x))
                   .Where(x => x.ToBeTermined == true);

The differences from the original ForEach are:

  1. Returns IEnumerable<T> instead of void.
  2. Works for every IEnumerable<T> and not just List<T>.

Upvotes: 1

STO
STO

Reputation: 10658

return myCollection.Where(determine).Select(x => { x.ToBeDetermined = true; return x; });

Upvotes: 0

Artem Mesha
Artem Mesha

Reputation: 157

Do it in two steps:

myCollection.ForEach(x => x.ToBeDetermined = determine(x));
return myCollection.Where(x => x.ToBeTermined == true);

Upvotes: 0

Knaģis
Knaģis

Reputation: 21485

Since you are setting a Boolean property and then filtering on it you can use this syntax:

return myCollection.Where(x => x.ToBeTermined = determine(x));

Note that you should at least write an explicit comment in the code because most people will see this as a typo and will be willing to "fix".

Upvotes: 3

Dimitri
Dimitri

Reputation: 7013

return myCollection
     .Select(x => {
                  x.ToBeDetermined = determine(x);
                  return x;
             })
     .Where(x => x.ToBeTermined == true);

Upvotes: 9

Related Questions