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... 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. Commented Nov 29, 2010 at 11:43

2 Answers 2

402

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);
Sign up to request clarification or add additional context in comments.

1 Comment

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.
16

Look at the ToLookup and/or ToDictionary extension methods.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.