如何将XML文件读取到字典< String,List&String>>空字符串为空元素 [英] How to read XML file to a Dictionary<String,List<String>> with empty strings for null elements
问题描述
我有一个xml文件,如:
I'm having an xml file like:
<root>
<RowDetails RowName="A" ColumnSize="1">
<ColumnDetails ColumnName="A1" />
</RowDetails>
<RowDetails RowName="B" ColumnSize="2">
<ColumnDetails ColumnName="B1" />
<ColumnDetails ColumnName="B2" />
</RowDetails>
<RowDetails RowName="C" ColumnSize="3">
<ColumnDetails ColumnName="C1" />
<ColumnDetails ColumnName="C2" />
<ColumnDetails ColumnName="C3" />
</RowDetails>
</root>
和一个字典如下:
Dictionary<String, List<String>>MyDict = new Dictioanary<String, List<String>>();
我正在将XML文件读入 MyDict
就像:
and i'm reading the XML file to MyDict
is like:
XDocument XDoc = XDocument.Load(Application.StartupPath + @"\foo.xml");
MyDict = XDoc.Descendants("RowDetails").ToDictionary(X => X.Attribute("RowName").Value,
X => X.Descendants("ColumnDetails")
.Select(Y => Y.Attribute("ColumnName").Value).ToList());
现在Dictionary将包含:
Now the Dictionary will contain:
"A" { "A1" }
"B" { "B1", "B2" }
"C" { "C1", "C2", "C3" }
但我的问题是我需要所有的列表相同的计数。应为空条目添加空字符串,因此预期结果为:
but my problem is that I need all the list with same count. Empty string should be added for null entry, so the expected result is:
"A" { "A1", "", "" }
"B" { "B1", "B2", "" }
"C" { "C1", "C2", "C3" }
如何修改我的LINQ查询?
How can I modify my LINQ query?
请帮我做使用LINQ。
Please help me to do this using LINQ.
提前感谢
推荐答案
假设你会就像这样做,在 MyDict
创建之后的后处理步骤中,基本思想是:
Assuming you would like this to be done as a post-processing step after MyDict
is created, the basic idea would be:
- 了解每个列表的大小应该如何(基于最大列表的计数)。
- 将每个列表与空字符串,以使其达到正确的大小。
- Find out what the size of each list should be (based on the count of the biggest list).
- Pad each list with empty strings as required to bring it up to the right size.
// The required size is the count of the biggest list
var sizeRequired = MyDict.Values.Max(l => l.Count);
// Pad each list as necessary
foreach (var list in MyDict.Values)
list.AddRange(Enumerable.Repeat(string.Empty, sizeRequired - list.Count));
这里有一种方法可以返回一个具有所需特征的新字典,而不使用原始集合:
Here's a way to return a new Dictionary with the required characteristics without mutating the original collection:
// The required size is the count of the biggest list
var sizeRequired = MyDict.Values.Max(l => l.Count);
// Each string key should map to a key in the new dictionary
// Each List<string> value should map to a new list, padded as necessary.
var paddedDict = MyDict.ToDictionary
(
kvp => kvp.Key,
kvp => kvp.Value
.Concat(Enumerable.Repeat(string.Empty, sizeRequired - kvp.Value.Count))
.ToList()
);
这篇关于如何将XML文件读取到字典< String,List&String>>空字符串为空元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!