Determine the presence of an element in a sequence with LINQ C#

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.

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: