我正在尝试创建一个使用List作为基础的自定义词典(将在XML反序列化中使用)。我无法弄清楚如何创建它,因为似乎键不能放在字符串上。
字典将具有TestObject的key属性作为Key,并且具有TestObject本身的Value。
public class TestObject
{
public string Key { get; set; }
public string Property1 { get; set; }
public int Property2 { get; set; }
}
public class CustomDictionary<string, TestObject> : List<TestObject>
{
}
public class Methods
{
public void TestMethod(List<TestObject> list)
{
var testObject = new TestObject()
{
Key = "TEST",
Property1 = "ABC",
Property2 = 123,
};
CustomDictionary<string, TestObject> dictionary = new CustomDictionary<string, TestObject>(list);
var test;
dictionary.TryGetValue(testObject.Key, out test);
}
}
鉴于你的最后评论,你想要做的是这样的:
public class Methods
{
public void TestMethod(List<TestObject> list)
{
Dictionary<string, TestObject> data = list.ToDictionary(x => x.Key);
}
}
这使用LINQ的ToDictionary
方法,虽然简单的foreach循环就足够了。