Determine the presence of an element in a sequence with LINQ C#
August 11, 2017 Leave a comment
Say we have the following string list:
string[] bands = { "ACDC", "Queen", "Aerosmith", "Iron Maiden", "Megadeth", "Metallica", "Cream", "Oasis", "Abba", "Blur", "Chic", "Eurythmics", "Genesis", "INXS", "Midnight Oil", "Kent", "Madness", "Manic Street Preachers" , "Noir Desir", "The Offspring", "Pink Floyd", "Rammstein", "Red Hot Chili Peppers", "Tears for Fears" , "Deep Purple", "KISS"};
The Any operator in LINQ has two versions. The paramaterless one simply returns true if the sequence contains at least one element:
bool exists = bands.Any(); Console.WriteLine(exists);
This yields true. The more exciting version of Any is where you can specify a filter in form of an element selector lambda:
bool exists = bands.Any(b => b.Length == 4); Console.WriteLine(exists);
This gives true as we have at least one element which consists of 4 characters. The below query returns false:
bool exists = bands.Any(b => b.EndsWith("hkhkj")); Console.WriteLine(exists);
You can view all LINQ-related posts on this blog here.