LINQ - is SkipWhile broken?

Posted by Judah Himango on Stack Overflow See other posts from Stack Overflow or by Judah Himango
Published on 2010-03-26T22:02:25Z Indexed on 2010/03/26 22:03 UTC
Read the original article Hit count: 430

Filed under:
|
|

I'm a bit surprised to find the results of the following code, where I simply want to remove all 3s from a sequence of ints:

var sequence = new [] { 1, 1, 2, 3 };
var result = sequence.SkipWhile(i => i == 3); // Oh noes! Returns { 1, 1, 2, 3 }

Why isn't 3 skipped?

My next thought was, OK, the Except operator will do the trick:

var sequence = new [] { 1, 1, 2, 3 };
var result = sequence.Except(i => i == 3); // Oh noes! Returns { 1, 2 }

In summary,

  • Except removes the 3, but also removes non-distinct elements. Grr.
  • SkipWhile doesn't skip the last element, even if it matches the condition. Grr.

Can someone explain why SkipWhile doesn't skip the last element? And can anyone suggest what LINQ operator I can use to remove the '3' from the sequence above?

© Stack Overflow or respective owner

Related posts about LINQ

Related posts about linq-to-objects