Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A dictionary with multiple entries with the same key [duplicate]

Tags:

c#

collections

I need a Dictionary like object that can store multiple entries with the same key. Is this avaliable as a standard collection, or do I need to roll my own?

To clarify, I want to be able to do something like this:

var dict = new Dictionary<int, String>(); dict.Add(1, "first"); dict.Add(1, "second");  foreach(string x in dict[1]) {     Console.WriteLine(x); } 

Output:

first second 
like image 266
oillio Avatar asked Sep 03 '10 22:09

oillio


People also ask

Can a dictionary have multiple of the same key?

Answer. No, each key in a dictionary should be unique. You can't have two keys with the same value. Attempting to use the same key again will just overwrite the previous value stored.

Can dictionary have duplicate keys in C#?

In Dictionary, the key cannot be null, but value can be. In Dictionary, key must be unique. Duplicate keys are not allowed if you try to use duplicate key then compiler will throw an exception. In Dictionary, you can only store same types of elements.

Can we repeat key in dictionary Python?

Python dictionary doesn't allow key to be repeated.


1 Answers

In .NET 3.5 you can use a Lookup instead of a Dictionary.

var items = new List<KeyValuePair<int, String>>(); items.Add(new KeyValuePair<int, String>(1, "first")); items.Add(new KeyValuePair<int, String>(1, "second")); var lookup = items.ToLookup(kvp => kvp.Key, kvp => kvp.Value);  foreach (string x in lookup[1]) {     Console.WriteLine(x); } 

The Lookup class is immutable. If you want a mutable version you can use EditableLookup from MiscUtil.

like image 65
Mark Byers Avatar answered Sep 22 '22 13:09

Mark Byers