LINQ query to return a Dictionary<string, string>
180,532
Solution 1
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
Look at the ToLookup
and/or ToDictionary
extension methods.
Related videos on Youtube
Author by
Scott Ivey
My areas of expertise include SQL, C#, and ASP.Net. My most recent Microsoft certifications include: MCSE:Business Intelligence MCSE:Data Platform MCSA:SQL Server 2012/2014 MCSD:Web Applications MCPD:Web MCPD:Windows MCITP:DB Developer MCITP:DBA
Updated on April 06, 2020Comments
-
Scott Ivey about 4 years
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()); }
-
Jon Skeet about 15 yearsWhat 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...
-
Fede over 13 yearsMaybe what you're looking for is the SortedDictionary implementation of IDictionary. Otherwise the sorting over a Dictionary is pointless.
-