LINQ-将列表转换为字典,并将值作为列表 [英] LINQ - Convert List to Dictionary with Value as List

查看:59
本文介绍了LINQ-将列表转换为字典,并将值作为列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个

List<MyObject> 

我从数据库中检索到的

.但是,我希望通过MyObject中的属性将其设置为分组目的.用LINQ将列表投射到的最佳方法是什么?

that I retrieve from the database. However, I would like it keyed by a property in MyObject for grouping purposes. What is the best way with LINQ to cast my list to:

Dictionary<long, List<MyObject>>

我有以下内容:

myObjectList.ToDictionary(x => x.KeyedProperty)

但是它返回:

Dictionary<long, MyObject>

推荐答案

听起来您想按KeyedPropertyMyObject实例进行分组,然后将该分组放入Dictionary<long,List<MyObject>>中.如果是这样,请尝试以下操作

It sounds like you want to group the MyObject instances by KeyedProperty and put that grouping into a Dictionary<long,List<MyObject>>. If so then try the following

List<MyObject> list = ...;
var map = list
  .GroupBy(x => x.KeyedProperty)
  .ToDictionary(x => x.Key, x => x.ToList());

这篇关于LINQ-将列表转换为字典,并将值作为列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆