Lijin Durairaj
Lijin Durairaj

Reputation: 5240

skipWhile in LINQ is not working as excepted

I am trying to learn LINQ and found out from MSD documentation that SkipWhile will tend to skip the value as long as the statement is true. however when I use this statement below I am not getting the result as expected.

int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
var allButFirst3Numbers = numbers.SkipWhile(x => x > 9);

foreach (var n in allButFirst3Numbers)
{
    Console.WriteLine(n);
}

From the code above the result should be

1,2,3,4,5,6,7,8,9

But I am getting the result as

1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15

Can anyone point out what exactly am I doing wrong in this, and how to get the expected result.

Upvotes: 0

Views: 1181

Answers (4)

Matthew Whited
Matthew Whited

Reputation: 22443

You are getting what you should get. You are saying skip while x > 9. 1 is less than 9 so it starts taking right away.

Try .SkipWhile(x=>x<=9) ... But that will give you 10,11,12,13,...

You may also try .TakeWhile(x=>x<=9) which will return 1,2,3,4,5,6,7,8,9

Upvotes: 1

Slai
Slai

Reputation: 22876

then you want to take, not skip

var numbers = Enumerable.Range(1, 15);
var result = numbers.TakeWhile(x => x <= 9);
Debug.Print(string.Join(", ", result)); // 1, 2, 3, 4, 5, 6, 7, 8, 9

Upvotes: 0

Rahul
Rahul

Reputation: 77896

The said predicate x => x > 9 will be match in the starting of the list and once that predicate is false it will go ahead and consider all the elements. You should rather try to use Where() extension method like

var allButFirst3Numbers = numbers.Where(x => x > 9);

Upvotes: 0

DavidG
DavidG

Reputation: 119017

From the docs for Enumerable.SkipWhile (emphasis mine):

This method tests each element of source by using predicate and skips the element if the result is true. After the predicate function returns false for an element, that element and the remaining elements in source are yielded and there are no more invocations of predicate.

So because the first element yields a false it will return everything. I suspect what you really wanted to write was:

var result = numbers.Where(x => x <= 9);

Upvotes: 7

Related Questions