简体   繁体   中英

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.

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);

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

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM