如何将linq表达式转换为字典<;字符串,字符串>;
本文关键字:字符串 gt lt 字典 linq 表达式 转换 | 更新日期: 2023-09-27 17:59:23
你能帮我如何将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"。集合。通用的字典"到"系统。集合。通用的IDictionary"。存在显式转换(是否缺少强制转换?)
同意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);
您遇到的问题是
dictionary.AsEnumerable().ToDictionary(x => x.CourseCode);
行执行您的查询。
在您检索数据的数据库中,您收到两次相同的CourseCode
,因此会收到错误消息:
"An item with the same key has already been added."
你的Distinct()
没有像你预期的那样表现,你必须检查一下。您希望按键进行distinct,但您正在对匿名key/Value调用distinct。