Reputation: 124
So i read this LINQ - Convert List to Dictionary with Value as List but am not able to get it working.
According to that post, I should be able to convert a list of items where several of them have the same key to a dictionary <int, List<>)
List<MyObject> list = ...;
var map = list
.GroupBy(x => x.KeyedProperty)
.ToDictionary(x => x.Key, x => x.ToList());
I have
MyObject
{
int OwnerId { get; set; }
string Description { get; set; }
}
List<MyObject> myObjects;
Now I want a dictionary with all objects that have the same OwnerId.
Dictionary<int, List<MyObjects> myObjects = ...
I tried to do
myObjects.GroupBy(x => x.OwnerId).ToDictionary(x => x.OwnerId, x => x.ToList());
problem is GroupBy returns a IGrouping<int, MyObject> and IGrouping does not have a property OwnerId. What did I miss?
Upvotes: 1
Views: 1439
Reputation: 16079
You need to use .Key
instead of .OwnerId
when you are creating a dictionary.
var resultantDictionary = myObjects
.GroupBy(x => x.OwnerId)
.ToDictionary(x => x.Key, x => x.ToList());
//^^^^ use .Key instead of .OwnerId
Upvotes: 3