LINQ query to return a Dictionary<string, string>

C#.NetLinqDictionary

C# Problem Overview


I have a collection of MyClass that I'd like to query using LINQ to get distinct values, and get back a Dictionary<string, string> as the result, but I can't figure out how I can do it any simpler than I'm doing below. What would some cleaner code be that I can use to get the Dictionary<string, 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());
}

C# Solutions


Solution 1 - C#

Use the ToDictionary method directly.

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);

Solution 2 - C#

Look at the ToLookup and/or ToDictionary extension methods.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionScott IveyView Question on Stackoverflow
Solution 1 - C#mmxView Answer on Stackoverflow
Solution 2 - C#leppieView Answer on Stackoverflow