How to populate a class using a dictionary using LINQ

In my project, I use XML to import various instances of the class. I need to import to a list. The problem is how to import all the "dynamicDrop" in the dictionary:

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 request:

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>();
+4
source share
1 answer

Here's how you can do it:

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

The trick is to use overloadSelect , which gives you two lambda parameters; the element itself and the element index.

+5
source

Source: https://habr.com/ru/post/1625634/


All Articles