Coder Perfect

LINQ allows you to select a dictionary T1, T2>.

Problem

I’ve utilized the “select” keyword and extension method to produce an IEnumerableT> using LINQ, but I’m having trouble figuring out how to return a generic DictionaryT1, T2>. The example I learned this from used something that sounded like this:

IEnumerable<T> coll = from x in y 
    select new SomeClass{ prop1 = value1, prop2 = value2 };

With extension methods, I’ve done the same thing. Because the items in a DictionaryT1, T2> may be iterated as KeyValuePairT1, T2>, I believed I could simply replace “SomeClass” in the preceding example with “new KeyValuePairT1, T2>…”, but that didn’t work (Key and Value were marked as readonly, so I could not compile this code).

Is this possible, or will I have to do it in stages?

Thanks.

Asked by Rich

Solution #1

A ToDictionary extension is also available using the extensions methods. The normal usage is to pass a lambda selection for the key and obtain the object as the value, however you can pass a lambda selector for both the key and the value.

class SomeObject
{
    public int ID { get; set; }
    public string Name { get; set; }
}

SomeObject[] objects = new SomeObject[]
{
    new SomeObject { ID = 1, Name = "Hello" },
    new SomeObject { ID = 2, Name = "World" }
};

Dictionary<int, string> objectDictionary = objects.ToDictionary(o => o.ID, o => o.Name);

The value “Hello” would then be found in objectDictionary[1].

Answered by Quintin Robinson

Solution #2

Projecting a collection to an IEnumerable of KeyValuePair and then converting it to a Dictionary is a more explicit option.

Dictionary<int, string> dictionary = objects
    .Select(x=> new KeyValuePair<int, string>(x.Id, x.Name))
    .ToDictionary(x=>x.Key, x=>x.Value);

Answered by Antoine Meltzheim

Solution #3

var dictionary = (from x in y 
                  select new SomeClass
                  {
                      prop1 = value1,
                      prop2 = value2
                  }
                  ).ToDictionary(item => item.prop1);

That is, assuming SomeClass.prop1 is the dictionary’s required Key.

Answered by albertein

Post is based on https://stackoverflow.com/questions/617283/select-a-dictionaryt1-t2-with-linq