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.
bool IsFisrtLetterR = names.AsQueryable().All(name => name.StartsWith("R")); Response.Output.Write("All Names start with letter \"R\": {0}<br />", IsFisrtLetterR); |

Join the conversation! Your thoughts help the community grow.