我想知道是否还有其他方法可以编写这么长的 Linq 代码?我所需要的只是角色的散列键和其客户名称的集合。
List<Customer> customers = await GetCustomers();
Dictionary<int, IEnumerable<string>> customersDict =
customers.GroupBy(x => x.RoleId).ToDictionary(x => x.Key, x => x.Select(v => v.Name));
Run Code Online (Sandbox Code Playgroud)
您可以使用ILookup<TKey, TElement>。
ILookup<int, string> customerNamesPerRoleId
= customers.ToLookup(c => c.RoleId, c => c.Name);
Run Code Online (Sandbox Code Playgroud)
Lookup 是不可变的,类似于字典。区别在于字典将键映射到单个值,而查找将键映射到值的集合。