Ilya Sulimanov
Ilya Sulimanov

Reputation: 7856

List object ToDictionary <object, List<object>>

public class User
{
   public string name { get; set; }
   public string login { get; set; }     
   public string company { get; set; }
}

How can I convert List<User> to ToDictionary<string, List<string>> where key : company value : names.

I try to do so

List<User> users = context.getallUsers();
var usersByCompany = users .ToDictionary<string, List<string>>(u => u.company, users.Where(d=>d.company==u.company).Select(c=>c.name).ToList()); 

Upvotes: 1

Views: 151

Answers (2)

Andrew
Andrew

Reputation: 3806

You may want to use ToLookup method:

ILookup<string, User> usersLookup = users.ToLookup(u => u.company);

usersLookup will be indexable by company

foreach (User u in userLookup["IBM"]) {...} //IBM users

if you still need company-name pairs, try following:

ILookup<string, string> usersLookup = users.ToLookup(u => u.company, u => u.name);

Upvotes: 1

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236308

First group users by company, then convert groups to dictionary:

users.GroupBy(u => u.company)
     .ToDictionary(g => g.Key,
                   g => g.Select(u => u.name).ToList());

Note: Type of dictionary will be inferred from usage.

Also you can consider to use ILookup<string, string> instead of Dictionary<string, List<string>>:

users.ToLookup(u => u.company, u => u.name)

Upvotes: 3

Related Questions