简体   繁体   中英

Strange Output in using SkipWhile() in LINQ

I was trying to workout the below example but get strange output for SkipWhile() operation it is not showing the expected output. Could some one explain why?

        List<Employees> emp = new List<Employees>();
        emp.Add(new Employees() { EmpId = 1, DeptId = 1, Salary = 20000 });
        emp.Add(new Employees() { EmpId = 2, DeptId = 2, Salary = 1000 });
        emp.Add(new Employees() { EmpId = 3, DeptId = 1, Salary = 3000 });
        emp.Add(new Employees() { EmpId = 4, DeptId = 3, Salary = 5000 });
        emp.Add(new Employees() { EmpId = 5, DeptId = 2, Salary = 4000 });


        var hsal = emp.OrderByDescending(x => x.Salary).GroupBy(x => x.DeptId).Select(x => x.FirstOrDefault());
        var secS = hsal.SkipWhile(x => x.Salary < 19000);
        foreach (Employees x in secS)
        {
            Console.WriteLine("Employer {0} of Dept {1} gets {2} as salary", x.EmpId, x.DeptId, x.Salary);
        }

The output I get is, but it should not produce any results since it has to skip the salary when it is less that 19000.

在此输入图像描述

SkipWhile does not skip all elements with the given condition but only all until this condition is met. If you want to skip all use Where :

var secS = hsal.Where(x => x.Salary >= 19000);

Output (why "should it not produce any results", there is one with salary=20000 ?) :

Employer 1 of Dept 1 gets 20000 as salary

The output looks correct to me.

The first item has a salary of 20000, which is not less than 19000.

Therefore the SkipWhile() skips nothing, because the predicate for the first item is false.

Thus, the entire list is returned in the foreach.

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