2014-01-10 63 views
0

我有以下LINQ查詢,我希望數據按照totalPopulation降序排列。如何使用LINQ獲取數據降序

var query = from u in xdoc.Root.Elements(ns + "DetailedUtility") 
      select new 
      { 
       UtilityId = (int)u.Attribute("UtilityId"), 
       TotalPopulation = u.Elements(ns + "City") 
            .Sum(c => (int)c.Attribute("Population")) 
      }; 

如何以降序獲取列表。 請幫助

+1

@Coelho,這個問題看起來更多的是關於排除故障的錯誤不是如何實現降序排列。 – Sam

回答

5
var query = (from u in xdoc.Root.Elements(ns + "DetailedUtility") 
      select new 
      { 
       UtilityId = (int)u.Attribute("UtilityId"), 
       TotalPopulation = u.Elements(ns + "City") 
            .Sum(c => (int)c.Attribute("Population")) 
      }).OrderByDescending(x => x.TotalPopulation); 

var query = from u in xdoc.Root.Elements(ns + "DetailedUtility") 
      let population = u.Elements(ns + "City") 
           .Sum(c => (int)c.Attribute("Population")) 
      orderby population descending 
      select new 
      { 
       UtilityId = (int)u.Attribute("UtilityId"), 
       TotalPopulation = population 
      }; 
+0

謝謝。它的工作:) –

0
var query = (from u in xdoc.Root.Elements(ns + "DetailedUtility") 
      select new 
      { 
       UtilityId = (int)u.Attribute("UtilityId"), 
       TotalPopulation = u.Elements(ns + "City") 
            .Sum(c => (int)c.Attribute("Population")) 
      }).OrderByDescending(x => x.TotalPopulation); 
+0

哈看起來像@MarchinJuraszek擊敗了我。好吧。 –