Reputation: 2569
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
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:
IEnumerable<T>
instead of void
.IEnumerable<T>
and not just List<T>
.Upvotes: 1
Reputation: 10658
return myCollection.Where(determine).Select(x => { x.ToBeDetermined = true; return x; });
Upvotes: 0
Reputation: 157
Do it in two steps:
myCollection.ForEach(x => x.ToBeDetermined = determine(x));
return myCollection.Where(x => x.ToBeTermined == true);
Upvotes: 0
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
Reputation: 7013
return myCollection
.Select(x => {
x.ToBeDetermined = determine(x);
return x;
})
.Where(x => x.ToBeTermined == true);
Upvotes: 9