LINQ:将OrderBy添加到查询中

时间:2012-04-16 16:26:27

标签: c# xml linq

我正处于我的大学项目的最后一行,而且我有点坚持完成一个查询。 工作查询如下所示:

var Report = from query in Document.Descendants("order")
                         group query by query.Element("seller").Value
                            into qGroup
                            select new Orders
                            {
                                Seller = qGroup.Key,
                                Quantity = qGroup.Sum(p => int.Parse(p.Element("quantity").Value)).ToString()
                            };

如果您能告诉我,如何按照给定的“数量”按降序排序结果,我将非常感激。

谢谢!

3 个答案:

答案 0 :(得分:3)

var Report = (from query in Document.Descendants("order")
              group query by query.Element("seller").Value into qGroup
              select new Orders
              {
                  Seller = qGroup.Key,
                  Quantity = qGroup.Sum(p => int.Parse(p.Element("quantity").Value)).ToString()
              })
              .OrderByDescending(order => order.Quantity);

答案 1 :(得分:0)

请这样做:

var Report = (from query in Document.Descendants("order")
                            group query by query.Element("seller").Value
                            into qGroup
                            select new Orders
                            {
                                Seller = qGroup.Key,
                                Quantity = qGroup.Sum(p => int.Parse(p.Element("quantity").Value)).ToString()
                            }).OrderByDescending(x => x.Quantity);

HTH !!!!

(感谢LINQ Orderby Descending Query

答案 2 :(得分:0)

Skippy和Andrei的答案有效,但你也可以写成

var Report = from query in Document.Descendants("order")
             group query by query.Element("seller").Value
             into qGroup
             let qty = qGroup.Sum(p =>int.Parse(p.Element("quantity").Value)).ToString()
             orderby qty descending
             select new Orders
             {
                 Seller = qGroup.Key,
                 Quantity = qty
             };

如果你想用一种语法保留它。