LINQ查詢返回Dictionary <string,string> - LINQ query to return a Dictionary<string, string>

問題:

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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章