Monday, April 14, 2014

All and Any with Lambda expressions

This simple Where Lambda will return an IEnumerable of the type it queries against, so bar must be a collection of MyType.

IEnumerable<MyType> foo = bar.Where(b => b.Status != (int)MyEnum.Whatever);

 
 

Bolting on All makes the Lambda return a true or false value.

Boolean foo = bar.Where(b => b.Status != (int)MyEnum.Whatever)
      .All(b => b.Whatever != null);

 
 

Bolting on Any does so too. The difference is that All makes sure that every record matches while Any looks for at least one match in the name of returning true.

Boolean foo = bar.Where(b => b.Status != (int)MyEnum.Whatever)
      .Any(b => b.Whatever != null);

No comments:

Post a Comment