Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Linq SkipWhile method is not working as expected

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading