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>();
List转Dictionary:
dict = list.ToLookup(item=> item.Id).ToDictionary(item=> item.Key, item=> item.First());
Dictionary转List:
list = dict.Values.ToList();
高效查找:
foreach (TestModel item in list)
{
if (dict.ContainsKey(item.Id))
{
TestModel model = dict[item.Id];
}
}