linq“让”分裂,然后顺序升序

时间:2013-06-04 17:49:48

标签: 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

3 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:2)

如果你只想按Inflation / GDP排序,你可以这样做:

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

或者用流利的语法:

var people = excel.Worksheet<CountryEconomics>("Sheet1")
                  .OrderBy(x => x.Inflation / x.GDP);

我不确定,但您可能需要跳过第一行(包含标题)。

var people = excel.Worksheet<CountryEconomics>("Sheet1")
                  .Skip(1).OrderBy(x => x.Inflation / x.GDP);

答案 2 :(得分:1)

现在,我只是猜测,但也许添加一些演员阵容会让它发挥作用:

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

然而,如果那也失败了 - 如果你先把它列为一个列表会发生什么:

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

如果仍然失败:

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

var peopleList = people.ToList().OrderBy(p => p);

希望这能完成......