LINQ Any and All Example in C#

LInq Any and All method returns a Boolean value from the query, if matching result found, returns true, otherwise false. Here we learn how to use Any All methods in LINQ C# example.

The All() method (of System.LINQ.Queryable class) returns a boolean value, check if all the elements of any collection satisfy the given condition.

LINQ All method in C#

Here is an example of using All method in LINQ
In following example we find out if all place name in the array starts with letter C

string[] placeArray = { "Calcutta", "Canada", "Costarica", "California", "Cameron", "Coimbatore" };
bool IsFisrtLetterC = placeArray.AsQueryable().All(p => p.StartsWith("C"));
bool IsLastLetterA = placeArray.AsQueryable().All(p => p.EndsWith("a"));
Console.WriteLine(IsFisrtLetterC); // true
Console.WriteLine(IsLastLetterA); // False
LINQ Any Method C# Example

The Any method (of System.LINQ.Queryable class) returns a boolean value, check if any of the elements of any collection satisfy the given condition.

Now let’s look at any method example
From below student list we check if any student has scored equal or more than 10

var studentsStream = new List<Student> {
new Student { FullName = "Aruna", StreamId=1, Score = 10 },
new Student { FullName = "Janet", StreamId=2, Score = 9 },
new Student { FullName = "Ajay", StreamId=1, Score = 11 },
new Student { FullName = "Kunal", StreamId=2, Score = 13 },
new Student { FullName = "Chandra", StreamId=2, Score = 8 },
};
bool hasScore10 = studentsStream.AsQueryable().Any(s => s.Score >= 10);
Console.WriteLine(hasScore10); // True

Note: here i have written the above code in console application to show you the output easily, you can write the same code in your razor page too, only make sure you have added the library reference, best practice would be write the code in c# file then call the method in razor page or your console file.

 
LINQ any and all method c# example: how to use any all in linq query
LINQ (language integrated query) allow you to write query on database objects like ado.net, entity framework etc, LINQ is type safe, easy to convert database object to list objects and business objects in secure and scalable way.
linq Interview Questions Answers
LINQ C# examples | Join Asp.net MVC Course