我有这个班

class Person
{
    public string idCard { get; set; }
    public string name { get; set; }
    public DateTime birthDate { get; set; }
}

以及一个对象列表
List<Person> list = new List<Person>(){
    new Person(){name="John",idCard="123",birthDate=new DateTime(1990,11,13)},
    new Person(){name="Paul",idCard="321",birthDate=new DateTime(1988,5,16)},
    new Person(){name="Clara",idCard="213",birthDate=new DateTime(1993,7,21)}
};

当我想不使用foreach将这个列表转换成字典时,对象的一个属性是键(我已经在web上搜索了所有的方法)
Dictionary<string, Person> personDict = new Dictionary<string,Person>();
personDict = list.GroupBy(x=>x.idCard).ToDictionary<string, Person>(x => x.Key,x=>x);

我还是有些错误
错误1实例参数:无法从“system.collections.generic.IEnumerable>”转换为“system.collections.generic.IEnumerable”G:\shuba\learning\experiments\testprogram\testprogram\program.cs 25 26 testprogram
错误4参数3:无法从“lambda expression”转换为“system.collections.generic.iequalitycomparer”G:\shuba\learning\experiments\testprogram\testprogram\program.cs 25 95 testprogram
错误3参数2:无法从“lambda expression”转换为“system.func”G:\shuba\learning\experiments\testprogram\testprogram.cs 25 83 testprogram
错误2“system.collections.generic.IEnumerable>”不包含“ToDictionary”的定义和最佳扩展方法重载“system.linq.Enumerable.ToDictionary(system.collections.generic.IEnumerable,system.func,system.collections.generic.iequalitycomparer)“有一些无效参数g:\shuba\learning\experiments\testprogram\testprogram.cs 25 26 testprogram
有人知道解决办法吗?
我想我是对的。

最佳答案

这将为您提供一个字典,其中键是idCard,值是Person对象。

Dictionary<string, Person> personDict = list.ToDictionary(x => x.idCard, y => y);

由于我们将把IdCard值作为字典键,如果列表中有多个具有相同ToDictionary值的项,ArgumentException方法调用将抛出一个idCard

10-06 07:53