Coder Perfect

Returning a Dictionarystring, string> with a LINQ query

Problem

I have a collection of MyClasses that I’d like to query with LINQ to retrieve distinct values and return a Dictionarystring, string> as a result, but I can’t think of a way to make it any easier than what I’m doing below. What would be some cleaner code to retrieve the Dictionarystring, string> as my result?

var desiredResults = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

var queryResults = (from MyClass mc in myClassCollection
                    orderby bp.SomePropToSortOn
                    select new KeyValuePair<string, string>(mc.KeyProp, mc.ValueProp)).Distinct();

foreach (var item in queryResults)
{
    desiredResults.Add(item.Key.ToString(), item.Value.ToString());
}

Asked by Scott Ivey

Solution #1

Directly use the ToDictionary method.

var result = 
  // as Jon Skeet pointed out, OrderBy is useless here, I just leave it 
  // show how to use OrderBy in a LINQ query
  myClassCollection.OrderBy(mc => mc.SomePropToSortOn)
                   .ToDictionary(mc => mc.KeyProp.ToString(), 
                                 mc => mc.ValueProp.ToString(), 
                                 StringComparer.OrdinalIgnoreCase);

Answered by mmx

Solution #2

Look into the extension methods ToLookup and/or ToDictionary.

Answered by leppie

Post is based on https://stackoverflow.com/questions/627867/linq-query-to-return-a-dictionarystring-string