gpt4 book ai didi

c# - 如何使用 LINQ 使用字典填充类

转载 作者:太空狗 更新时间:2023-10-30 01:02:09 25 4
gpt4 key购买 nike

在我的项目中,我使用 XML 导入类的各种实例。我需要导入一个列表。问题是如何在字典中导入所有“dynamicDrop”:

XML:

<LootProfile name="volpeNormale">
<dynamicDropNumber>3</dynamicDropNumber>
<dynamicDrop>70</dynamicDrop>
<dynamicDrop>40</dynamicDrop>
<dynamicDrop>10</dynamicDrop>
<dynamicTypeArmor>33</dynamicTypeArmor>
<dynamicTypeWeapon>33</dynamicTypeWeapon>
<dynamicTypeConsumable>34</dynamicTypeConsumable>
<dynamicRarityCommon>70</dynamicRarityCommon>
<dynamicRarityUncommon>20</dynamicRarityUncommon>
<dynamicRarityRare>8</dynamicRarityRare>
<dynamicRarityEpic>2</dynamicRarityEpic>
<staticDropNumber>2</staticDropNumber>
<staticDrop idPattern="100">60</staticDrop>
<staticDrop idPattern="145">100</staticDrop>
<faction>All</faction>
<location>All</location>
</LootProfile>

XMLImporter 查询:

var query = from item in xml.Root.Elements("LootProfile")
select new LootProfile()
{
name = (string)item.Attribute("name"),
dynamicDropNumber = (int)item.Element("dynamicDropNumber"),
dynamicDrop = (Dictionary<int,string>)item.Element("dynamicDrop) //this one doesnt work!
//other element....
}
return query.ToList<LootProfile>();

最佳答案

这里是你如何做到的:

var query = xml.Elements("LootProfile")
.Select(item => new LootProfile()
{
name = (string) item.Attribute("name"),
dynamicDropNumber = (int) item.Element("dynamicDropNumber"),
dynamicDrop =
item.Elements("dynamicDrop")
.Select((Item, Index) => new {Item, Index})
.ToDictionary(x => x.Index, x => float.Parse(x.Item.Value))
//other element....
});

var result = query.ToList();

诀窍是使用 overload of Select这给了你两个 lambda 参数;项目本身,以及项目的索引。

关于c# - 如何使用 LINQ 使用字典填充类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34963865/

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