views:

8358

answers:

3

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

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);
Mehrdad Afshari
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
+2  A: 

Look at the ToLookup and/or ToDictionary extension methods.

leppie
A: 

Look at the code sample to perforn sorting on Dictinary and return Dictionary from LINQ query result at below my blog: http://nileshhirapra.blogspot.com/2010/08/sorting-dictionary-using-linq-and-using.html

Nilesh Hirapra