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.

Advertisement

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

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

  1. Armugam Indrani says:

    Can you give some example regarding, SkipWhile(s,i,bool) , plz…

    • Andras Nemes says:

      You have one right there in the post:

      SkipWhile((s, i) => s.Length < 10 && i < 10);

      Func(s, i, bool) is a function that accepts a string – as we're dealing with an IEnumerable of strings -, a loop parameter and returns a boolean. That's exactly what the example entails.
      //Andras

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

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: