248

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());
}
2
  • 7
    What do you want it to do with duplicate keys? Just take the first and ignore subsequent ones? Be aware that dictionaries aren't ordered, so your ordering in the query will have no effect...
    – Jon Skeet
    Commented Mar 9, 2009 at 20:25
  • 1
    Maybe what you're looking for is the SortedDictionary implementation of IDictionary. Otherwise the sorting over a Dictionary is pointless.
    – Fede
    Commented Nov 29, 2010 at 11:43

2 Answers 2

401

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);
1
  • 1
    Mehrdad, thanks for the pointer on this. This was the direction I was going in, but for must have been overlooking the correct overload of ToDictionary.
    – Scott Ivey
    Commented Mar 9, 2009 at 20:35
16

Look at the ToLookup and/or ToDictionary extension methods.

Not the answer you're looking for? Browse other questions tagged or ask your own question.