SuicideSheep
SuicideSheep

Reputation: 5550

C# Lambda expression update value to nullable field

Please take a look at code below:

SomeList.Where(x => !x.Name.Equals("NO")).All(x => x.flag=true);

SomeList is a ICollection

For each of the object in SomeList, if the Name is not NO, flag of the object should be updated to be true. Now the problem is the flag is bool?

How should I assign value to the flag in such lambda expression?

Upvotes: 1

Views: 1113

Answers (1)

Nikola Radosavljević
Nikola Radosavljević

Reputation: 6911

What you are essentially trying to do is avoid using foreach which is fruitless business. Alexander's answer uses ForEach extension method, but then you also must materialize a list using ToList method.

Most elegant approach is to just use foreach loop.

foreach (var item in SomeList.Where(x => !x.Name.Equals("NO")))
    item.flag = true;

If you really want to have an functional programming style of invoking an action on all members of a collection, either write your own extension method or use Ix.NET which already provides such helper extensions.

var n = 0;
Enumerable.Range(0, 10).Do(x => n += x)

It provides following overloads

IEnumerable<TSource> Do<TSource>(this IEnumerable<TSource> source, Action<TSource> onNext)
IEnumerable<TSource> Do<TSource>(this IEnumerable<TSource> source, Action<TSource> onNext, Action onCompleted)
IEnumerable<TSource> Do<TSource>(this IEnumerable<TSource> source, Action<TSource> onNext, Action<Exception> onError)
IEnumerable<TSource> Do<TSource>(this IEnumerable<TSource> source, Action<TSource> onNext, Action<Exception> onError, Action onCompleted)
IEnumerable<TSource> Do<TSource>(this IEnumerable<TSource> source, IObserver<TSource> observer)

Upvotes: 4

Related Questions