A SkipWhile question

  • Thread starter Thread starter Ilyas
  • Start date Start date
I

Ilyas

Hi all

I have the following code:

List<int> items1 = new List<int>() { 1, 2, 3, 4, 5 };

items1.SkipWhile(i => i % 2 == 1).ToList()));

this produces {2,3,4,5} I was epecting 2,4

Can anyone explain? - I'm trying to get al the even numbers
 
Ilyas said:
I have the following code:

List<int> items1 = new List<int>() { 1, 2, 3, 4, 5 };

items1.SkipWhile(i => i % 2 == 1).ToList()));

this produces {2,3,4,5} I was epecting 2,4

Can anyone explain?

From the docs:

<quote>
Bypasses elements in a sequence as long as a specified condition is
true and then returns the remaining elements.
</quote>

In other words, it bypasses just the first element (because the
condition is true), then returns the rest of the elements because the
condition is false for the second element.
I'm trying to get al the even numbers

In that case you want to use Where, which applies a filter to *every*
element.


Take/TakeWhile/Skip/SkipWhile are all about returning/ignoring the
first part of the sequence, up to a particular point - where that point
is either specified by "the first element to fail a predicate" or an
index. After that, the rest of the sequence is ignored/returned.
 
--
Anthony Jones - MVP ASP/ASP.NET
Ilyas said:
Hi all

I have the following code:

List<int> items1 = new List<int>() { 1, 2, 3, 4, 5 };

items1.SkipWhile(i => i % 2 == 1).ToList()));

this produces {2,3,4,5} I was epecting 2,4

Can anyone explain? - I'm trying to get al the even numbers

From MSDN:-

Bypasses elements in a sequence as long as a specified condition is true and
then returns the remaining elements

So its doing what it says it does. Note that it does not continue to test
the condition once it has been satisified.

What your looking for is a .Where(i => i % 2 == 1)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top