【问题标题】:Getting Rounded Values in the final result of Linq Query在 Linq Query 的最终结果中获取舍入值
【发布时间】:2014-07-21 09:49:05
【问题描述】:

如何修改下面的 linq 查询,以便我可以得到一个四舍五入的数值。

                 var result=GetStudentsWithTheirMarks()                
                .OrderByDescending(x => Math.Round(x.PercentageScore)).Take(5)                 
                .OrderBy(x => x.PercentageScore);

请忽略两个 order by 子句的存在,因为这样做是有目的的。 GetStudentsWithThierMarks 返回学生列表及其名字和百分比分数。 我相信上述查询 Math.Round 仅在按操作排序期间适用,因此最终结果仍包含小数位的值,而我只对具有整数值的四舍五入数字感兴趣。我只是想不通语法。

【问题讨论】:

    标签: c# .net linq lambda


    【解决方案1】:

    你只需要一个Select

    var result= GetStudentsWithTheirMarks()                
                .OrderByDescending(x => Math.Round(x.PercentageScore))
                .Take(5)                 
                .OrderBy(x => x.PercentageScore)
                .Select(x => Math.Round(x.PercentageScore));
    

    【讨论】:

    • 嗨 Selman22 我知道这就是语法,但是一旦我把它放在我的查询中,我的 order by 子句就有语法问题,请您发布完整的查询。谢谢
    • 什么是错误
    • 抱歉。我的错误是我的方法中有不同的返回类型。所以谢谢你的回答
    【解决方案2】:

    您可以将此值存储在匿名类型中:

    var result = GetStudentsWithTheirMarks()    
      .Select(s => new 
      { 
          Student = s, 
          RoundedPercentageScore = Math.Round(s.PercentageScore) 
      })          
      .OrderByDescending(x => x.RoundedPercentageScore )
      .Take(5)                 
      .OrderBy(x => x.Student.PercentageScore);
    

    现在可以这样访问了:

    foreach(var x in result)
        Console.WriteLine("RoundedPercentageScore: " x.RoundedPercentageScore);
    

    【讨论】:

    • 嗨蒂姆感谢您的回复。在第一部分 OrderByDescending 子句会给出语法错误。
    • @Sike12:你确定你用过我上面贴的代码吗?我没有看到您的语法错误的原因。
    • 道歉。我的错误是我的方法中有不同的返回类型。所以谢谢你的回答
    猜你喜欢
    • 2011-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-01
    • 2019-06-04
    • 2014-03-21
    • 2015-12-12
    • 1970-01-01
    相关资源
    最近更新 更多