I often need one key to multiple vaules dictionary, but in C# most of them are two dimensions like Dictionary and Hashtable.
I want something like this:
var d = new Dictionary<key-dt,value1-dt,value2-dt,value3-dt,value4-dt>();
dt inside<> means data type. Anybody has ideas about this?
General Idea: In Python, if we want a dictionary to have multiple values for a single key, we need to store these values in their own container within the dictionary. To do so, we need to use a container as a value and add our multiple values to that container. Common containers are lists, tuples, and sets.
In python, if we want a dictionary in which one key has multiple values, then we need to associate an object with each key as value. This value object should be capable of having various values inside it. We can either use a tuple or a list as a value in the dictionary to associate multiple values with a key.
Create an Array Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value. To declare an array, define the variable type with square brackets: string[] cars; We have now declared a variable that holds an array of strings.
It's a dictionary of dictionaries, so you have 2 keys to access each object, the key for the main dictionary to get you the required sub dictionary, and then the second key for the sub dictionary to get you the required item.
A dictionary is a key-value pair, where the value is fetched depending on the key. The keys are all unique.
Now if you want a Dictionary
with 1 keytype and multiple value types, you have a few options:
first is to use a Tuple
var dict = new Dictionary<KeyType, Tuple<string, string, bool, int>>()
The other is to use (with C# 4.0 and above):
var dict = new Dictionary<KeyType, dynamic>()
the System.Dynamic.ExpandoObject
can have value of any type.
using System;
using System.Linq;
using System.Collections.Generic;
public class Test {
public static void Main(string[] args) {
dynamic d1 = new System.Dynamic.ExpandoObject();
var dict = new Dictionary<int, dynamic>();
dict[1] = d1;
dict[1].FooBar = "Aniket";
Console.WriteLine(dict[1].FooBar);
dict[1].FooBar = new {s1="Hello", s2="World", s3=10};
Console.WriteLine(dict[1].FooBar.s1);
Console.WriteLine(dict[1].FooBar.s3);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With