All operator in linq

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.

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);
            result = intArray.All(i => i < 6);

Here in the above code I have taken integer array. I have perform two things, In first condition I have checked that all the elements of integer array is less then two or not and second condition I have checked that all the elements are less then six or not. So as per above code first condition should return false and second condition should return true. Let’s run application.


That’s it. Output is as expected. Hope you like it. Stay tuned for more..
Shout it


Popular posts from this blog

How to create Rest API(Web API) with ASP.NET Core 1.0

Creating PDF with ASP.Net MVC and RazorPDF

Solution: gulp is not recognized as internal or external command- Visual Studio