你能幫助我,如何將linq表達式轉換爲字典?以下代碼引發了我ArgumentException:具有相同鍵的項目已被添加。如何將linq表達式轉換爲字典<string,string>
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'是你需要的嗎? –
paul
不,每個課程必須始終只在一個區域提供。這是學校的功課,我必須觀察界面,所以我不能更改Dictionary –
user3553299
那麼在那種情況下,我會查看您的數據。如果每個課程代碼只存在於一個領域,那麼你的第一次嘗試就會奏效,而你不應該需要'Distinct' – paul