Selecting a subset of elements in LINQ C# with the SkipWhile operator

The SkipWhile operator is similar to Skip. With Skip we omit the first n elements where n is an integer. With SkipWhile you can define a boolean condition. The elements will be skipped until the condition is true.

Example data source:

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 following query will keep skipping the items until it finds one which is at least 10 characters long:

IEnumerable<string> res = bands.SkipWhile(s => s.Length < 10);
foreach (string item in res)
{
	Console.WriteLine(item);
}

The first item to be selected and printed on the Console window is “Iron Maiden” as it is exactly 10 characters long. The remaining elements in the array will be selected as the initial condition has been fulfilled.

SkipWhile has an overload where you can specify the loop parameter. The following query will keep skipping items until it finds one which is at least 10 characters long OR the tenth element has been reached:

IEnumerable<string> res2 = bands.SkipWhile((s, i) => s.Length < 10 && i < 10);
foreach (string item in res2)
{
	Console.WriteLine(item);
}

This query yields the same result as the one above as “Iron Maiden” is the 4th element so the “s.Length less than 10” condition has been reached first.

View the list of posts on LINQ 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: