如何使用 LINQ 用字典填充类
本文关键字:填充 字典 何使用 LINQ | 更新日期: 2023-09-27 18:31:30
在我的项目中,我使用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 query:
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();
诀窍是使用 Select
重载,为您提供两个 lambda 参数:项目本身和项目的索引。