c#
  • .net
  • linq
  • sql-order-by
  • 2010-11-03 100 views 0 likes 
    0

    我有下面的代碼從一個字符串中提取關鍵字:添加OrderByDescending到LINQ聲明

    var results = text.Split(new char[]{' ',',','.','!','?','_',':',';','/','(',')','\n','\r','-','*','"','/','\\','$','%','+','-','='})               // default split by whitespace 
        .GroupBy(str => str)  // group words by the value 
        .Select(g => new 
           { 
            str = g.Key,      // the value 
            count = g.Count() // the count of that value 
           }); 
    

    現在我需要添加OrderByDescending它,但不知道在哪裏把它。 .GroupBy(str => str).OrderByDescending(count => count)產生了不正確的結果。如何使它正確?

    回答

    4

    您可以在選擇後添加它。

    .Select(...whatever...).OrderByDescending(item => item.count); 
    
    +1

    +1以獲得更好的性能。請參閱[我的答案](http://stackoverflow.com/questions/4088064/add-orderbydescending-to-linq-statement/4088088#4088088)以獲得解釋。 – 2010-11-03 14:54:13

    2

    中的GroupBy後使用它,並呼籲g.Count()你在Select聲明沒有以同樣的方式:

    .GroupBy(str => str) 
    .OrderByDescending(g => g.Count()) 
    .Select(g => new ...) // rest of your code here 
    

    編輯:其實我更喜歡Anthony's answer我自己,正要修改我的,但那時他已經發布他的迴應。這是一個非常小的問題,並且是一個不成熟的優化,但是由於Count()正在執行兩次,所以在處理大型集合時,我的發佈方法會稍微慢一些,而Anthony的方法是對Select聲明中已計算的Count()進行排序。在構建乾淨的LINQ查詢時請注意。另外,在查詢語法中,我們可以通過將計數存儲在let(當然,這可以在流暢的語法中可能,但在查詢語法中感覺更自然)來解決這個問題,這將提供良好的性能。類似這樣的:

    var query = from g in text.Split(...).GroupBy(str => str) 
          let count = g.Count() 
          orderby count descending 
          select new { str = g.Key, Count = count }; 
    
    2

    你誤會是因爲你在lambda中給變量賦予了與匿名類型屬性相同的名稱。​​3210排序整個對象。你想要的是對count屬性進行排序,所以你應該使用OrderByDescending(x => x.count)

    相關問題