![](/img/trans.png)
[英]How to convert Dictionary<string, string> to attribute string in LINQ?
[英]How to convert linq expression to dictionary<string,string>
您能幫我,如何將linq表達式轉換成字典? 以下代碼拋出ArgumentException:具有相同鍵的項已添加。
IDictionary<string, string> listAllCoursesWithAreaAsDictionary = new Dictionary<string, string>();
var dictionary =
(from b in bookListRecord
select new { b.CourseCode, b.Area }).Distinct();
listAllCoursesWithAreaAsDictionary = dictionary.AsEnumerable().ToDictionary(x => x.CourseCode, x => x.Area);
return listAllCoursesWithAreaAsDictionary;
當我嘗試這個:
listAllCoursesWithAreaAsDictionary = dictionary.AsEnumerable().ToDictionary(x => x.CourseCode);
我收到錯誤消息:無法將類型'System.Collections.Generic.Dictionary'隱式轉換為'System.Collections.Generic.IDictionary'。 存在顯式轉換(您是否缺少演員表?)
您遇到的問題是
dictionary.AsEnumerable().ToDictionary(x => x.CourseCode);
行執行您的查詢。
在您從中檢索數據的數據庫中,您兩次收到相同的CourseCode
,因此收到錯誤消息:
"An item with the same key has already been added."
您的Distinct()
行為不符合您的預期,您必須進行檢查。 您想按鍵區分,但是您要對匿名鍵/值進行區分。
同意Aharon,您正在尋找分組運算符:
var dictionary = bookListRecord
.GroupBy(g => g.CourseCode)
.Select(g => new { g.Key,
AreaList = g.Select(c => c.Area).ToList(),
Area = g.Select(c => c.Area).FirstOrDefault() })
.ToDictionary(g => g.Key);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.