使用Linq列出到字典转换

Dan*_*iel 3 c# list

有人可以建议我使用Linq运算符来编写一个优雅的代码来将List转换为List of Dictionary吗?例如.我有一个person(List<Person>)列表,我想将其转换为列表字典(比如Dictionary<string, List<Person>>使用该人的姓氏作为密钥.我需要快速查找姓氏列表

Phi*_*lip 7

获得一个Dictionary<string, List<Person>>来自List<Person>:

var dictionary = list
                   .GroupBy(p => p.LastName)
                   .ToDictionary(g => g.Key, g => g.ToList());
Run Code Online (Sandbox Code Playgroud)