gpt4 book ai didi

C# 列表到没有 Foreach 的字典 [错误]

转载 作者:太空狗 更新时间:2023-10-30 00:50:01 27 4
gpt4 key购买 nike

我有这门课

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 的情况下将该列表转换为字典时,其中对象的属性之一是键(我一直在网上搜索以做到这一点)

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

还有一些错误

Error 1 Instance argument: cannot convert from 'System.Collections.Generic.IEnumerable>' to 'System.Collections.Generic.IEnumerable' G:\SHUBA\Learning\Experiments\TestProgram\TestProgram\Program.cs 25 26 TestProgram Error 4 Argument 3: cannot convert from 'lambda expression' to 'System.Collections.Generic.IEqualityComparer' G:\SHUBA\Learning\Experiments\TestProgram\TestProgram\Program.cs 25 95 TestProgram Error 3 Argument 2: cannot convert from 'lambda expression' to 'System.Func' G:\SHUBA\Learning\Experiments\TestProgram\TestProgram\Program.cs 25 83 TestProgram Error 2 'System.Collections.Generic.IEnumerable>' does not contain a definition for 'ToDictionary' and the best extension method overload 'System.Linq.Enumerable.ToDictionary(System.Collections.Generic.IEnumerable, System.Func, System.Collections.Generic.IEqualityComparer)' has some invalid arguments G:\SHUBA\Learning\Experiments\TestProgram\TestProgram\Program.cs 25 26 TestProgram

有人知道解决办法吗?

我想我是对的。

最佳答案

这应该给你一个字典,其中键是 idCard,值是 Person 对象。

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

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

关于C# 列表到没有 Foreach 的字典 [错误],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34376436/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com