C # Listing in a dictionary without bias [ERROR]

I have this class

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

and list of objects

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)}
};

When I want to convert this list to a dictionary without foreach, where one of the attributes of the object is the key (I searched all this to do this on the Internet)

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

I still have errors

1 : 'System.Collections.Generic.IEnumerable > ' 'System.Collections.Generic.IEnumerable' G:\SHUBA\Learning\Experiments\TestProgram\TestProgram\Program.cs 25 26 TestProgram 4 3: lambda '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\Program.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\Program.cs 25 26 TestProgram

- ?

, .

+4
2

, idCard, Person.

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

idCard , ToDictionary ArgumentException idCard.

+3

, ToDictionary . :

var personDict = list.ToDictionary(p => p.idCard);

Btw. personDict .

+3
source

Source: https://habr.com/ru/post/1620926/


All Articles