c# 如何使用 XElement 计算组合元素值的总数
c# How do I count the total of combined element values using XElement
我有一个包含数千个条目的 XElement 片段。我需要能够计算每个唯一 ID 元素的 qty 元素的组合值
举个例子,我有数百种用于维修程序的消耗品(用品),每一种都有唯一的 ID(见下文)。如果 ID 是一种经常使用的消耗品,它可能会在我的 XElement 片段中被调用 50 次,并且它在 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(在本示例中为 16)的所有 qty 元素的值相加,然后将所有供应 ID 27(即 1)的值相加,供应相同ID 16(即 2)。我需要为数百个唯一 ID 执行此操作。
我不介意如何向我显示每个 ID 的总和,如果需要,可以通过向每个 ID 添加一个元素来调用 'Total'。
知道如何实现吗?
您可以使用 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());
}
}
}
我有一个包含数千个条目的 XElement 片段。我需要能够计算每个唯一 ID 元素的 qty 元素的组合值
举个例子,我有数百种用于维修程序的消耗品(用品),每一种都有唯一的 ID(见下文)。如果 ID 是一种经常使用的消耗品,它可能会在我的 XElement 片段中被调用 50 次,并且它在 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(在本示例中为 16)的所有 qty 元素的值相加,然后将所有供应 ID 27(即 1)的值相加,供应相同ID 16(即 2)。我需要为数百个唯一 ID 执行此操作。
我不介意如何向我显示每个 ID 的总和,如果需要,可以通过向每个 ID 添加一个元素来调用 'Total'。
知道如何实现吗?
您可以使用 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());
}
}
}