Determine if all elements fulfil a condition in a sequence with LINQ C#
June 6, 2014 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"};
Say we’d like to determine if all elements in the sequence fulfil a certain condition. Nothing could be easier using the All operator:
bool all = bands.All(b => b.StartsWith("A")); Console.WriteLine(all);
This yields false as not all band names start with an A. However, their length is certainly longer than 2 characters so the below query returns true:
bool all = bands.All(b => b.Length > 2); Console.WriteLine(all);
You can view all LINQ-related posts on this blog here.