Saturday, March 16, 2013

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

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.

AllOperatorinLinq

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

0 comments:

Post a Comment

Your feedback is very important to me. Please provide your feedback via putting comments.

About Me
My Photo

Full Stack Developer,Blogger,Microsoft Mvp, Mentor, Life long learner, 10+ Years of Experience for JavaScript, web and Microsoft technologies. ASP.NET MVC,Web Forms,C#,AngularJs,Golang
Mvp profile
Subscribe to my blog

Enter your email address:

Follow us on facebook
Blog Archive
Total Pageviews