Skip to content

Instantly share code, notes, and snippets.

@ishu3101
Last active January 16, 2021 22:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ishu3101/4a5846860fc268d0fc7323171e2d92ff to your computer and use it in GitHub Desktop.
Save ishu3101/4a5846860fc268d0fc7323171e2d92ff to your computer and use it in GitHub Desktop.
Dictionary with Single Key and Multiple Values Example in C#. See https://repl.it/CY3S/1 to run example code online.
using System;
using System.Collections.Generic;
class MainClass {
public static void Main (string[] args) {
Dictionary<string, List<String>> map = new Dictionary<string, List<String>>();
// create list one and store values
List<string> valSetOne = new List<string>();
valSetOne.Add("Apple");
valSetOne.Add("Aeroplane");
// create list two and store values
List<String> valSetTwo = new List<String>();
valSetTwo.Add("Bat");
valSetTwo.Add("Banana");
// create list three and store values
List<String> valSetThree = new List<String>();
valSetThree.Add("Cat");
valSetThree.Add("Car");
// add values into map
map.Add("A", valSetOne);
map.Add("B", valSetTwo);
map.Add("C", valSetThree);
// iterate and display values
foreach(KeyValuePair<string, List<string>> kvp in map){
foreach(string value in kvp.Value){
Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, value);
}
}
}
}
@mehedisaurav
Copy link

mehedisaurav commented Aug 26, 2018

How can I delete 'Aeroplane' from valSetOne after adding into map?

@h26k2
Copy link

h26k2 commented Sep 24, 2018

Here's how you can delete value from multi-valued dictionary,

dictionaryName["KeyThatContainsThatValue"].RemoveAt(indexOftheValue);

Example :
map["A"].RemoveAt(1);

@OfficialVreesie
Copy link

And how can I update only 1 value in a multi value dictionary?

@tanmay-18
Copy link

Now I want to add 4th Item which is a single string (not a list) in the same (map) dictionary. How can I do this?

@Yousha
Copy link

Yousha commented May 2, 2020

Using new MultiValueDictionary is an option: https://www.nuget.org/packages/Microsoft.Experimental.Collections

@VedantGirkar
Copy link

VedantGirkar commented Jun 20, 2020

Out of the whole Dictionary I only want Aeroplane. How do I do that?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment