Priadhana Edi Kresnha
Priadhana Edi Kresnha

Reputation: 65

C# List to Dictionary without Foreach [ERROR]

I have this class

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

and a 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 that list into dictionary without foreach, where one of the object's attributes is the key (I have searched all the way to do that in the web)

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

I still got some errors

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

Does anyone know the solution?

I think I have it right.

Upvotes: 4

Views: 699

Answers (2)

Shyju
Shyju

Reputation: 218732

This should give you a dictionary where the key is the idCard and value is the Person object.

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

Since we are going to make the IdCard value as the dictionary key, The ToDictionary method call will throw an ArgumentException if your list has more than one item with same idCard value.

Upvotes: 3

Ondrej Svejdar
Ondrej Svejdar

Reputation: 22054

The grouping is not necessary, ToDictionary does it for you. This should be simple as:

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

Btw. there is no need to declare variable personDict and assign it to empty dictionary in first step & reassign it one line later.

Upvotes: 3

Related Questions