【问题标题】:Strange Output in using SkipWhile() in LINQ在 LINQ 中使用 SkipWhile() 的奇怪输出
【发布时间】:2015-06-05 02:46:58
【问题描述】:

我试图锻炼下面的例子,但得到了 SkipWhile() 操作的奇怪输出,它没有显示预期的输出。有人能解释一下原因吗?

        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);
        }

我得到的输出是,但它不应该产生任何结果,因为它必须在低于 19000 时跳过工资。

【问题讨论】:

    标签: c# linq


    【解决方案1】:

    SkipWhile 不会跳过具有给定条件的 所有 元素,而只会跳过所有元素,直到满足该条件。如果你想跳过所有使用Where:

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

    输出(为什么“不应该产生任何结果”,有一个salary=20000?)

    Employer 1 of Dept 1 gets 20000 as salary
    

    【讨论】:

      【解决方案2】:

      输出对我来说是正确的。

      第一项工资20000,不低于19000。

      因此SkipWhile() 什么都不跳过,因为第一项的谓词是假的。

      因此,整个列表在 foreach 中返回。

      【讨论】:

      • 第一条记录不满足条件,其他记录满足条件。那为什么输出中没有跳过满意的记录呢?
      • @Venkat Read the documentationReturns: An IEnumerable&lt;T&gt; that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate.
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多