LINQ - 按名称分组到Dictionary <string,List <T >>

Dan*_*dry 1 c# linq dictionary

我正在构建一个库应用程序.我有一个书籍列表,其中一些书籍有一个重复的名称(同一本书的副本很少).我想将列表转换为Dictionary>,其中字符串将是书的名称,List将包含具有此名称的所有Book对象.

我成功地做到了这一点:

var result  = queriedBooks
                .GroupBy(b => b.Name)
                .Where(g => g.Count() >= 1)
                .ToDictionary(b => b.Key, /// );
Run Code Online (Sandbox Code Playgroud)

这是我被卡住的地方.我不知道该作为一个值传递什么.Intellisense也没有帮助,因为没有Value可用的属性.我想避免使用匿名对象,因为每个Book条目都有许多我在视图中使用的属性.

非常感谢你!

Yac*_*sad 6

你应该ToList()像这样使用:

.ToDictionary(b => b.Key, b => b.ToList());
Run Code Online (Sandbox Code Playgroud)

每个小组都有一个Key属性,这是关键.它(组)也IEnumerable<Book>代表组中的项目,这就是为什么ToList()有效.


Dmi*_*nko 6

作为替代方案,您可能只想要Lookup<String, Book>而不是使用combersome Dictionary<String, List<Book>>:

   LookUp<String, Book> result = queriedBooks
     .ToLookup(book => book.Name);
Run Code Online (Sandbox Code Playgroud)

在以下情况下Dictionary<String, List<Book>>:

   var result = queriedBooks
     .GroupBy(book => book.Name) 
     .ToDictionary(chunk => chunk.Key, chunk => chunk.ToList());
Run Code Online (Sandbox Code Playgroud)

请注意,这.Where(g => g.Count() >= 1)多余的 ;