在 C# 中,可以使用 ToDictionary() 方法将一个 List 转换为 Dictionary。
假设我们有一个包含 Person 对象的 List:
List<Person> persons = new List<Person>
{
new Person { Id = 1, Name = "Alice" },
new Person { Id = 2, Name = "Bob" },
new Person { Id = 3, Name = "Charlie" }
};
我们想要将这个 List 转换为一个 Dictionary,其中 Person 对象的 Id 作为 Key,Person 对象本身作为 Value。 可以使用如下代码:
Dictionary<int, Person> dict = persons.ToDictionary(p => p.Id);
上述代码中,ToDictionary() 方法接受一个 lambda 表达式作为参数,该 lambda 表达式指定了将 List 中的每个元素转换为 Dictionary 的 Key 和 Value。在本例中,lambda 表达式为 p => p.Id,表示将 Person 对象的 Id 属性作为 Key,Person 对象本身作为 Value。
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
// 创建 Person 对象的 List
List<Person> persons = new List<Person>
{
new Person { Id = 1, Name = "Alice" },
new Person { Id = 2, Name = "Bob" },
new Person { Id = 3, Name = "Charlie" }
};
// 将 List 转换为 Dictionary
Dictionary<int, Person> dict = persons.ToDictionary(p => p.Id);
// 输出 Dictionary 中的元素
foreach (KeyValuePair<int, Person> kvp in dict)
{
Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value.Name}");
}
}
}
class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
运行结果如下:
Key: 1, Value: Alice
Key: 2, Value: Bob
Key: 3, Value: Charlie