Last active
January 16, 2021 22:14
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} | |
} |
Here's how you can delete value from multi-valued dictionary,
dictionaryName["KeyThatContainsThatValue"].RemoveAt(indexOftheValue);
Example :
map["A"].RemoveAt(1);
And how can I update only 1 value in a multi value dictionary?
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?
Using new MultiValueDictionary
is an option: https://www.nuget.org/packages/Microsoft.Experimental.Collections
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
How can I delete 'Aeroplane' from valSetOne after adding into map?