使用Linq创建字典

5

如何使用Linq创建一个Dictionary(或者更好的是ConcurrentDictionary)呢?

例如,如果我有以下XML:

<students>
    <student name="fred" address="home" avg="70" />
    <student name="wilma" address="home, HM" avg="88" />
    .
    . (more <student> blocks)
    .
</students>

如果我想把数据加载到XDocument doc;并且想用一个ConcurrentDictionary<string, Info>(其中键是名称,Info是保存地址和平均值的类。填充Info现在不是我的问题),我该如何做呢?


1
“使用LINQ”是一种要求还是一种趋势? - Vlad
1
可能是重复问题:https://dev59.com/OHI-5IYBdhLWcg3wta_w - Christian
2个回答

9
XDocument xDoc = XDocument.Parse(xml);
var dict = xDoc.Descendants("student")
                .ToDictionary(x => x.Attribute("name").Value, 
                              x => new Info{ 
                                  Addr=x.Attribute("address").Value,
                                  Avg = x.Attribute("avg").Value });


var cDict = new ConcurrentDictionary<string, Info>(dict);

如果ConcurrentDictionary是必须的,最好跳过.ToDictionary,并直接在foreach循环中将序列加载到空的ConcurrentDictionary中。这样可以避免创建一个被丢弃的Dictionarydict)。 - spender

3

这样的东西就可以了:

var dict = xml.Descendants("student")
              .ToDictionary(r => (string)r.Attribute("name").Value, r => CreateInfo(r));

这将产生一个普通的Dictionary; 您可以从普通的Dictionary构建一个ConcurrentDictionary

@Jaroslaw:不,实际上有问题吗?如果有的话,您可以帮助改进答案(或提供自己的答案)。 - Vlad
如果你有时间,只需运行此代码,因此你将会收到一个错误。我不明白将异常贴在注释中的意义所在。这只是给你查看的提示,对于我来说可以保持原样。 - jwaliszko
@Jaroslaw:我手头没有编译器。当然,重点是帮助读者知道正确的答案。 - Vlad
嗯,@Jaroslaw 为什么这么难懂呢?与此同时,我建议读取属性值而不是子元素值。 - spender
@Vlad:好的,还有一个问题,将xml.Descendants("students")替换为xml.Descendants("student"),这样可以获得更多节点而不仅仅是主节点。 - jwaliszko

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接