How to use Any, All and Aggregate in LINQ


Prologue:

LINQ is very powerful for querying any source of data; the data source can be collections of objects, databases or XML files. We can easily retrieve data from any object that implements the IEnumerable<T> interface.

Let us see how to use the Any, All and Aggregate methods in LINQ.

Any Method:

The Any method of System.LINQ.Queryable class returns a Boolean value if any element of the provided data source sequence satisfies the applied test condition. It returns true even if a single element satisfies the condition otherwise false if none of the elements pass the test. Example 1:  the First overloaded method of LINQ Any method takes no parameter. It only checks whether the collection has any element or not:

                                                                             

string[] names = { };

bool IsEmpty = names.AsQueryable().Any();

Response.Output.Write("IsEmpty: {0}<br />", IsEmpty);


Example 2: The second overloaded method takes one parameter as a predicate that applies a test condition on each element of the sequence:

 
    class A
{
}
class B
{
}

class C
{
}

List<object> objList = new List<object>()
{
new A(),new B(),new C()
};

if (objList.Any(obj => obj is A))
{
Console.WriteLine("One object is of Type A");
}

Normal 0 false false false EN-IN X-NONE X-NONE MicrosoftInternetExplorer4

In this above code we are checking whether any one of the objects in the object List is of type A.

Normal 0 false false false EN-IN X-NONE X-NONE MicrosoftInternetExplorer4

All Method:

The All method of System.LINQ.Queryable class returns a Boolean value if all the elements of the sequence satisfy the provided condition. It returns true if all the elements satisfy the condition otherwise it returns false.

Example 1: The example condition will test each element of the sequence to check whether it starts with "R" or not.          

 
                 
  string[] names = { "Ram", "Raj", "Remo","Ravi", "Rangila" };

                   bool IsFisrtLetterR = names.AsQueryable().All(name => name.StartsWith("R"));

                    Response.Output.Write("All Names start with letter \"R\": {0}<br />", IsFisrtLetterR);



Normal 0 false false false EN-IN X-NONE X-NONE MicrosoftInternetExplorer4

Example 2: we have used the LINQ All method in the LINQ query expression to get the students having all marks greater than 70.
 List<Student> Students = new List<Student>() 

    {
        new Student(101, "Hugo", "Garcia", new List<int>() { 91, 88, 76, 93 }),
        new Student(102, "Rick", "Adams", new List<int>() { 70, 73, 66, 90 }),
        new Student(103, "Michael", "Tucker", new List<int>() { 73, 80, 75, 88 }),
        new Student(104, "Fadi", "Fakhouri", new List<int>() { 82, 75, 66, 84 }),
        new Student(105, "Peter", "Barrows", new List<int>() { 67, 78, 70, 82 })
    };

    var query = from student in Students
                where student.Marks.AsQueryable().All(m => m > 70)
                select student;

    foreach (Student student in query)
    {
        Response.Output.Write("{0} {1}<br />", student.FirstName, student.LastName);
    }


Normal 0 false false false EN-IN X-NONE X-NONE MicrosoftInternetExplorer4

Aggregate Method:

The Aggregate method makes it simple to perform a calculation over a sequence of values. This method works by calling func one time for each element in source. Each time func is called, Aggregate passes both the element from the sequence and an aggregated value (as the first argument to func). The first element of source is used as the initial aggregate value. The result of func replaces the previous aggregated value. Aggregate returns the final result of func.
Example 1:

 string sentence = "the quick brown fox jumps over the lazy dog";

// Split the string into individual words.
string[] words = sentence.Split(' ');
// Join each word to the beginning of the new sentence to reverse the word oder.

string reversed = words.Aggregate(( workingSentence, next) => next + " " + workingSentence);
Console.WriteLine(reversed);
/*
This code produces the following output:

dog lazy the over jumps fox brown quick the
*/

Example 2:
List<int> SampleList = new List<int>() { 1, 1, 2, 3, 5, 8, 13 };
int AggCount = SampleList.Aggregate((counter, listItem) => counter += listItem);
Console.WriteLine(string.Format("Aggregate count is: {0}", AggCount));

// Outputs:
// Aggregate count is: 33

 

Note that most LINQ providers will probably have difficulties to support Aggregate in its entirety, simply because it's so flexible. You can use Aggregate to do sums, products, divisions, string concatenations, list building, and much, much, more

Summary:

Normal 0 false false false EN-IN X-NONE X-NONE

In this article, we have seen the various methods in LINQ usefull in various scenarios.

Thanks for spending your precious time here. Please provide your valuable feedbacks and comments, which enables me to give a better article in the future.

Thanks.

Up Next
    Ebook Download
    View all
    Learn
    View all