如何将linq表达式转换为字典<string,string> </string,string>

时间:2014-04-22 09:17:27

标签: c# linq todictionary

你能帮助我,如何将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'。存在显式转换(您是否错过了演员?)

2 个答案:

答案 0 :(得分:0)

你遇到的问题是

dictionary.AsEnumerable().ToDictionary(x => x.CourseCode); 

行执行您的查询。

在您从中检索数据的数据库中,您收到两次相同的CourseCode,因此您收到错误消息:

"An item with the same key has already been added."

Distinct()的行为与您的预期不符,您必须检查一下。您希望按键区分,但是您在匿名键/值上调用distinct。

答案 1 :(得分:0)

同意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);