LINQ-按名称分组为Dictionary< string,List< T>>. [英] LINQ - grouping by name to Dictionary<string, List<T>>
问题描述
我正在构建图书馆应用.我有一本书的清单,其中有些书名重复(同一本书的副本很少).我想将列表转换为Dictionary>,其中字符串将是一本书的名称,而List将包含具有该名称的所有Book对象.
I am building a library app. I have a list of Books where some of them have a duplicate name (there are few copies of the same book). I would like to convert the list to Dictionary>, where the string would be the name of a book, and the List would contain all the Book objects with this name.
我已经设法做到了这一点:
I've managed to get this far:
var result = queriedBooks
.GroupBy(b => b.Name)
.Where(g => g.Count() >= 1)
.ToDictionary(b => b.Key, /// );
这就是我被困住的地方.我不知道该如何传递价值. Intellisense也无济于事,因为没有可用的Value
属性.我想避免使用匿名对象,因为每个Book条目都有许多我在视图中使用的属性.
This is where I get stuck. I have no idea what to pass as a value. Intellisense does not help either, as there is no Value
property available. I would like to avoid using anonymous objects, as each Book entry has many properties which I use in a view.
非常感谢!
推荐答案
作为替代方案,您可能只需要Lookup<String, Book>
而不是麻烦的Dictionary<String, List<Book>>
:
As an alternative you may want just Lookup<String, Book>
instead of combersome Dictionary<String, List<Book>>
:
LookUp<String, Book> result = queriedBooks
.ToLookup(book => book.Name);
对于Dictionary<String, List<Book>>
:
var result = queriedBooks
.GroupBy(book => book.Name)
.ToDictionary(chunk => chunk.Key, chunk => chunk.ToList());
请注意,.Where(g => g.Count() >= 1)
是冗余;
这篇关于LINQ-按名称分组为Dictionary< string,List< T>>.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!