問題:
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. 我有一個MyClass的集合,我想用LINQ來查詢獲取不同的值,然後得到一個Dictionary <string,string>作爲結果,但我無法弄清楚我怎麼能比我更簡單我在下面做。 What would some cleaner code be that I can use to get the Dictionary<string, string> as my result? 一些更乾淨的代碼可以用來獲取Dictionary <string,string>作爲我的結果?
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());
}
解決方案:
參考一: https://en.stackoom.com/question/2dKt參考二: https://stackoom.com/question/2dKt