c#如何使用XElement计算组合元素值的总和

问题描述 投票:0回答:1

我有一个包含数千个条目的XElement片段。我需要能够计算每个唯一ID元素的qty元素的组合值

举个例子,我有几百个用于维修程序的消耗品(用品),每个消耗品都有一个唯一的ID(见下文)。如果它是一个经常使用的耗材,那么在我的XElement片段中可能会调用50次ID,并且它在qty元素中的值可能大于1。我需要迭代我的XElement片段,计算每个ID的qty元素值的总和。

<supplies>
     <supply>
        <id>104</id>
        <qty>1</qty>
     </supply>
     <supply>
        <id>27</id>
        <qty>1</qty>
     </supply>
     <supply>
        <id>104</id>
        <qty>5</qty>
     </supply>
     <supply>
        <id>104</id>
        <qty>10</qty>
     </supply>
     <supply>
        <id>16</id>
        <qty>2</qty>
     </supply>
</supplies>

在此示例中,我需要将供应ID 104的所有qty元素(在此示例中为16)中的值相加,然后将所有供应ID 27(其为1)的值与供应ID 16的相同值(即2)。我需要为数百个唯一ID执行此操作。

我并不担心每个人的总和是如何呈现给我的,可能是通过在每个ID中添加一个元素,如果必要的话也可以称为“总计”。

知道怎么做到这一点好吗?

c# xml linq-to-xml
1个回答
0
投票

您可以使用xml linq和字典来获得所需的结果

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            Dictionary<int, int> dict = doc.Descendants("supply")
                .GroupBy(x => (int)x.Element("id"), y => (int)y.Element("qty"))
                .ToDictionary(x => x.Key, y => y.Sum());
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.