c# - linq "let"除法,然后按升序排序

标签 c# linq linq-to-excel

我有这些数据,我正在使用 linqToExcel: enter image description here

我试图用通货膨胀率除以 GDP...然后按升序排序,但我做错了。

    var people = from x in excel.Worksheet<CountryEconomics>("Sheet1")
                 let c = x.Inflation / x.GDP
                 orderby c ascending 
                 select c;

我得到了输出:

12
6
4
3
2
2

无论我在查询中使用升序还是降序。我怎样才能让数据升序?即

2
2
3
4
6
12

最佳答案

MSDN orderby clause

var people = from x in excel.Worksheet<CountryEconomics>("Sheet1")
             let c = x.Inflation / x.GDP
             orderby c
             select c;  

我不能只用数组重现:

var economics = new[]
    {
        new {Country = "USA", GDP = 1, Inflation = 12},
        new {Country = "GB", GDP = 2, Inflation = 12},
        new {Country = "JPN", GDP = 3, Inflation = 12},
        new {Country = "GER", GDP = 4, Inflation = 12},
        new {Country = "CHI", GDP = 5, Inflation = 12},
        new {Country = "CAN", GDP = 6, Inflation = 12},
    };

var people = from x in economics
             let c = x.Inflation/x.GDP
             orderby c
             select c;

// without "orderby c":  12, 6, 4, 3, 2, 2
// with "orderby c":  2, 2, 3, 4, 6, 12
Console.WriteLine(string.Join(", ", people));

这可能是 Linq-to-Excel 的缺陷。 (我无法对此进行测试。)

如果是这种情况,您可以强制求值(通过下面的 .ToArray())然后对其进行排序。作为使用 LINQ 的任何静态数据的使用者,我期望 ToArray 调用是不必要的。

var people = from x in economics
             let c = x.Inflation/x.GDP
             select c;

var sorted = people.ToArray().OrderBy(c => c);
Console.WriteLine(string.Join(", ", sorted));

关于c# - linq "let"除法,然后按升序排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16924302/

相关文章:

c# - "wrong"单元格上的 LinqToExcel 异常处理

c# - 如何避免和预测内存不足异常

c# - 它是否从数据库加载数据?

c# - 从数据库表中选择两行

xml - 使用 LINQ 对属性进行 VB XML 查询

c# - 使用linq按子集合的属性进行过滤

c# - 使用 Neo4j .Net 驱动程序的结果

c# - Sbyte[] 与 byte[][] 使用方法

c# - 在 asp.net mvc 中检查上传的 Excel 文件中的非法字符

c# - 使用 LinqToExcel 创建 XML