C# List与Dictionary相互转换与高效查找
程序员文章站
2022-06-10 17:50:07
TestModel类定义: public class TestModel{ public int Id { get; set; } public string Name { get; set; } public string Code { get; set; } } Dictionary与List定 ......
testmodel类定义:
public class testmodel
{
public int id { get; set; }
public string name { get; set; }
public string code { get; set; }
}
dictionary与list定义:
list<testmodel> list = new list<testmodel>();
dictionary<int, testmodel> dict = new dictionary<int, testmodel>();
dictionary转list:
dict = list.tolookup(model => model.id).todictionary(model => model.key, model => model.first());
list转dictionary:
list = dict.values.tolist();
高效查找:
foreach (testmodel item in list)
{
if (dict.containskey(item.id))
{
testmodel model = dict[item.id];
}
}
下一篇: 当你消极的时候,缓缓心情。