Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List to Dictionary<Key, List<Value>> - C#

I have a List and MyClass is:

public class MyClass
{
    public bool Selected { get; set; }
    public Guid NoticeID { get; set; }
    public Guid TypeID { get; set; }
}

My question is, how do i convert this list into a Dictionary<Guid, List<Guid>>, where the dictionary key is the GUID from the TypeID property, and the value is a list of all the NoticeID values corresponding to that TypeID. I have tried like so:

list.GroupBy(p => p.TypeID).ToDictionary(p => p.Key, p => p.ToList())

but this returns a Dictionary <Guid, List<MyClass>>, and I want a Dictionary<Guid, List<Guid>>.

like image 646
raresm Avatar asked Mar 13 '15 07:03

raresm


People also ask

Can dictionary KEY be a list in C#?

Dictionary keys must be comparable for equality, must present a proper hash code, and must be immutable. These requirements make it a little bit involved to use lists as dictionary keys since lists don't typically provide value semantics - in this case, item by item comparison and a proper hash code.

Which is faster list or dictionary in C#?

Of course the Dictionary in principle has a faster lookup with O(1) while the lookup performance of a List is an O(n) operation. The Dictionary map a key to a value and cannot have duplicate keys, whereas a list just contains a collection of values. Also Lists allow duplicate items and support linear traversal.


1 Answers

Well, when you group you can specify the value you want for each element of the group:

var dictionary = list.GroupBy(p => p.TypeID, p => p.NoticeID)
                     .ToDictionary(p => p.Key, p => p.ToList());

However, I would strongly consider using a lookup instead of a dictionary:

var lookup = list.ToLookup(p => p.TypeID, p => p.NoticeID);

Lookups are much cleaner in general:

  • They're immutable, whereas your approach ends up with lists which can be modified
  • They express in the type system exactly what you're trying to express (one key to multiple values)
  • They make looking keys up easier by returning an empty sequence of values for missing keys, rather than throwing an exception
like image 195
Jon Skeet Avatar answered Oct 19 '22 02:10

Jon Skeet