Tho*_*eld 4 c# xml linq dictionary
我有一个xml文件,如:
<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>
Run Code Online (Sandbox Code Playgroud)
和一个像这样的词典:
Dictionary<String, List<String>>MyDict = new Dictioanary<String, List<String>>();
Run Code Online (Sandbox Code Playgroud)
我正在读取XML文件,MyDict如:
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());
Run Code Online (Sandbox Code Playgroud)
现在字典将包含:
"A" { "A1" }
"B" { "B1", "B2" }
"C" { "C1", "C2", "C3" }
Run Code Online (Sandbox Code Playgroud)
但我的问题是我需要所有列表具有相同的计数.应为空条目添加空字符串,因此预期结果为:
"A" { "A1", "", "" }
"B" { "B1", "B2", "" }
"C" { "C1", "C2", "C3" }
Run Code Online (Sandbox Code Playgroud)
如何修改LINQ查询?
请帮我用LINQ做这个.
提前致谢.
假设您希望在MyDict创建之后将其作为后处理步骤完成,基本思路将是:
// 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));
Run Code Online (Sandbox Code Playgroud)
这是一种返回具有所需特征的新词典而不改变原始集合的方法:
// 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()
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4955 次 |
| 最近记录: |