【问题标题】:Select distinct customers and sum orders from XML file using LINQ使用 LINQ 从 XML 文件中选择不同的客户和订单总和
【发布时间】:2013-01-26 16:12:42
【问题描述】:

到目前为止,我有一个简单的 LINQ 查询,它使用 XML 文件来构建字典或 customerid 和订单:

var Limit = from c in xml.Descendants("Customer") 选择新的 { customerID = c.Descendants("customerid").First().Value, order = c.Descendants("order").First().Value,

                          };

我需要返回不同的客户 ID 以及每个客户 ID 的“订单”总数。例如我有:

客户 ID = 123 订单 = 200

客户 ID = 123 订单 = 100

客户 ID = 123 订单 = 50

客户 ID = 456 订单 = 100

客户 ID = 456 订单 = 100

我需要:

客户 ID = 123 OrderTotal = 350

客户 ID = 456 OrderTotal = 200

我知道有很多类似的问题,但我对 LINQ 还是很陌生。

谢谢

【问题讨论】:

    标签: linq-to-xml sum distinct


    【解决方案1】:

    如果没有看到确切的 XML 输入结构,很难编写代码,但请尝试以下几行:

    var query = from cust in xml.Descendants("Customer")
                group cust by (int)cust.Element("customerid") into g
                select new {
                  customerID = g.Key,
                  total = g.Elements("order").Sum(el => (decimal)el)
                }
    

    [编辑] 使用您想要的评论中提到的示例

    var query = from cust in xml.Descendants("Customer")
                group cust by (int)cust.Element("customerid") into g
                select new {
                  customerID = g.Key,
                  total = g.Elements("ordertotal").Sum(el => (decimal)el)
                }
    

    【讨论】:

    • 我的XML如下 123100123 300456100
    猜你喜欢
    • 1970-01-01
    • 2013-02-16
    • 2011-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多