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


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(item=> item.Id).ToDictionary(item=> item.Key, item=> item.First());

 

List转Dictionary

list = dict.Values.ToList();

 

高效查找:

foreach (TestModel item in list)
{
    if (dict.ContainsKey(item.Id))
    {
        TestModel model = dict[item.Id];
    }
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM