smark91
smark91

Reputation: 625

How to populate a Class with Dictionary using LINQ

In my project I use an XML to import various instances of a class. I need to import in a List. The problem is how to import all "dynamicDrop" in a 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 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>();

Upvotes: 4

Views: 380

Answers (1)

Yacoub Massad
Yacoub Massad

Reputation: 27871

Here is 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 an overload of Select that gives you two lambda parameters; the item itself, and the index of the item.

Upvotes: 5

Related Questions