Linq SkipWhile method is not working as expected

Advertisements

I trying to write a program using Linq SkipWhile() method, output is not as expected. and not to use orderby method for sorting.
Here is my Program:

using System;
using System.Linq;
using System.Collections.Generic;
                                
public class Program
{
    public static void Main()
    {
        IList<int> numbersList = new List<int>(){ 1, 4, 5, 6, 7, 8, 9, 10, 2, 3 };
        
        var result = numbersList.SkipWhile((x, i) => i > 4 && x > 4);
        
        foreach(var num in result)
            Console.WriteLine(num);
        
    }
}

Output
1
4
5
6
7
8
9
10
2
3

am i doing something wrong in this program?

Expected Output
8
9
10

>Solution :

SkipWhile – skips the elements of the sequence until they satisfy its condition, and then returns all the remaining elements.

In your example, already the first number in the sequence does not satisfy the requirement (1 < 4), so it just returns the entire sequence.

For your expected result, you can use two options:

var result = numbersList.OrderBy(x => x).SkipWhile(x => x<8);
var result2 = numbersList.Where(x => x >= 8);

Leave a ReplyCancel reply