Few days back I came across “All” operator in Linq. I thought it will be good idea to write a blog post about it and share it with community.
It check the condition whether all the elements on collection matches given criteria and based on that it will return bool value. It can be useful in scenario where we need to do some kind of validation whether all the elements of collection matches with certain condition or not.
So Let’s take a simple example. Following is a code for that.
All operator in linq:
It’s almost similar to select it returns all the element in the input sequence with matching condition in given predicate. Following is syntax for All.public static bool All<TSource>( this IEnumerable<TSource> source, Func<TSource, bool> predicate)
It check the condition whether all the elements on collection matches given criteria and based on that it will return bool value. It can be useful in scenario where we need to do some kind of validation whether all the elements of collection matches with certain condition or not.
So Let’s take a simple example. Following is a code for that.
using System; using System.Linq; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { int[] intArray = {1,2,3,4,5}; bool result = intArray.All(i => i > 2); Console.WriteLine(result); result = intArray.All(i => i < 6); Console.WriteLine(result); } } }