gpt4 book ai didi

c# - 使用 Linq 创建字典

转载 作者:太空狗 更新时间:2023-10-30 00:11:20 25 4
gpt4 key购买 nike

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

例如,如果我有以下 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 不是我关心的问题),我该怎么做?

最佳答案

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);

关于c# - 使用 Linq 创建字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13451929/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com