2016-01-23 51 views
4

在我的項目中,我使用XML來導入類的各種實例。 我需要在列表中導入。 問題是如何導入所有的 「dynamicDrop」 在詞典:如何使用LINQ使用字典填充類

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

'dynamicDrop'字典的預期內容是什麼? –

+0

字典索引包含從0到DynamicDropNumber的int,content是DynamicDrop xml元素值。在給定的xml字典中是0,70 - 1,40 - 2,10 – smark91

+0

是的,dynamicDrop看起來更像是一個整數列表。琴絃應該從哪裏來?如果你只是想要一個整數列表,我認爲你可以做這樣的事情(對不起,我不能把換行符,使這更可讀):dynamicDrop = item.Elements(「dynamicDrop」)。Select(x =>(int )x).ToList()(對不起,如果這不起作用,我沒有在一段時間內使用XML LINQ) – ekolis

回答

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參數ERS;項目本身以及項目的索引。

+0

相當可觀! – Fattie

+1

謝謝@JoeBlow –

+0

非常感謝的人!奇蹟般有效! – smark91