2013-06-04 31 views
3

我有這樣的數據,我使用linqToExcel: enter image description hereLINQ「let」的劃分,然後排序依據上行

我試圖讓通脹除以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 
+0

那麼問題是什麼?在什麼地方卡住了? –

+1

_我無法正確理解_你得到了什麼輸出,你期望什麼? –

+0

我無法按升序排列,對不起。 – marseilles84

回答

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

希望這能做到...

+0

太棒了!最後兩個在這裏工作。感謝您的迴應。 – marseilles84

+0

不客氣! –

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); 
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到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)); 
+0

如果我在第三行添加「orderby c ascending」,我得到的結果與輸入降序相同。 – marseilles84

+0

@ marseilles84:看到我對這個問題的評論。你真的需要說明你正在接受什麼與你期望的相比。我們不知道是什麼。 –