简体   繁体   中英

C# - Convert List to Dictionary with Value as List

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM