Selecting a subset of elements in LINQ C# with the SkipWhile operator
July 29, 2014 2 Comments
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.
Can you give some example regarding, SkipWhile(s,i,bool) , plz…
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