简体   繁体   English

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

[英]How to convert linq expression to dictionary<string,string>

can you help me, how to convert linq expression to dictionary? 您能帮我,如何将linq表达式转换成字典? The following code is throwing me ArgumentException: An item with the same key has already been added. 以下代码抛出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;

When I try this: 当我尝试这个:

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

I get error: Cannot implicitly convert type 'System.Collections.Generic.Dictionary' to 'System.Collections.Generic.IDictionary'. 我收到错误消息:无法将类型'System.Collections.Generic.Dictionary'隐式转换为'System.Collections.Generic.IDictionary'。 An explicit conversion exists (are you missing a cast?) 存在显式转换(您是否缺少演员表?)

The problem you are having is that the 您遇到的问题是

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

line executes your query. 行执行您的查询。

In your database, where you retrieve your data from, you are receiving the same CourseCode twice, hence you get the error message: 在您从中检索数据的数据库中,您两次收到相同的CourseCode ,因此收到错误消息:

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

Your Distinct() doesn't behave as might you expect, you will have to check that. 您的Distinct()行为不符合您的预期,您必须进行检查。 You wanted distinct by key, but you are calling distinct on an anonymous Key/Value. 您想按键区分,但是您要对匿名键/值进行区分。

Agreed with Aharon, you're looking for grouping operator: 同意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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM