与此处解决的问题有关:How to populate a Class with Dictionary using LINQ
我还有另一个问题是尝试填充Dictionary<ObjectType, float>
,其中ObjectType是我创建的自定义枚举。
LootProfile.cs
public class LootProfile
{
/*
dynamicDrop multipli non definiti
*/
public string name;
public int dynamicDropNumber; // = 3
public Dictionary<int, float> dynamicDrop; // 70, 40, 10
public Dictionary<ObjectType, float> dynamicType;
public Dictionary<Rarity, float> dynamicDropRarity; // "Common" - 60, "Uncommon" - 26, "Rare" - 12, "Epic" - 2
public int staticDropNumber; // = 2
public Dictionary<int, Dictionary<int, float>> staticDrop; // 0 - idPattern - prob
public Faction faction;
public Location location;
}
ImporterXML
var query = from item in xml.Root.Elements("LootProfile")
select 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)),
dynamicType = item.Elements("dynamicTypeArmor")
.Select((Item, Index) => new { Item, Index })
.ToDictionary(x => x.Index, x => float.Parse(x.Item.Value))
}
return query.ToList<LootProfile>();
我的问题是如何在Dictionary中导入XML元素的值
dynamicTypeArmor
dynamicTypeWeapon
dynamicTypeConsumable
在同一个词典中
ObjectType.Armor for dynamicTypeArmor
ObjectType.Weapon for dynamicTypeWeapon
ObjectType.Consumable for dynamicTypeConsumable
答案 0 :(得分:1)
以下是如何做到这一点:
var query = xml.Elements("LootProfile")
.Select(item => new LootProfile()
{
//...
dynamicType =
item.Elements()
.Where(x => x.Name.LocalName.StartsWith("dynamicType"))
.ToDictionary(
x => (ObjectType)Enum.Parse(
typeof(ObjectType),
x.Name.LocalName.Substring("dynamicType".Length)),
x => float.Parse(x.Value))
//...
});
您使用Where
仅选择名称以&#34; dynamicType&#34;开头的元素,然后从数据中创建字典。
每个字典项的键是删除&#34; dynamicType&#34;后相应元素名称的其余部分。这将为你提供&#34;护甲&#34;,&#34;武器&#34;或&#34;消耗品&#34;。 Enum.Parse
用于将这些字符串转换为Enum
类型ObjectType
。
每个字典项的值是解析为float的相应元素的值。