欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C# List与Dictionary相互转换与高效查找

程序员文章站 2023-10-28 19:57:28
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];
    }
}