Bick
Bick

Reputation: 18551

populate a dictionary using linq

I have the following empty Dictionary

Dictionary<Guid, string> appTypeMap = new Dictionary<Guid, string>();

and the following list:

List<ApplicationType> allApplicationTypes = _applicationTypeService.GetAll()

Application type is described as follows:

public class ApplicationType
{
   public Guid id {get; set;}
   public String name {get; set;}
}

I want to populate the dictionary using LINQ.
How do I do that? Thanks.

Upvotes: 46

Views: 29958

Answers (2)

Mike C.
Mike C.

Reputation: 3114

Try

appTypeMap = _applicationTypeService.GetAll().Select(o => new DictionaryEntry{
  Key = o.id,
  Value = o.name
}).ToList();

Not sure if you need a .ToList() on the end....

Upvotes: 3

MarcinJuraszek
MarcinJuraszek

Reputation: 125660

appTypeMap = allApplicationTypes.ToDictionary(x => x.id, x => x.name);

However, it will create a new dictionary, not fill yours.

Upvotes: 97

Related Questions