如何使用LINQ用Dictionary填充类

时间:2016-01-23 13:12:05

标签: c# linq unity3d

在我的项目中,我使用XML导入类的各种实例。 我需要在List中导入。 问题是如何在词典中导入所有“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>();

1 个答案:

答案 0 :(得分:5)

以下是如何做到这一点:

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参数;项目本身以及项目的索引。