C # dictionary with multiple key values

I am using a C # dictionary.

Dictionary<int, string> d = new Dictionary<int, string>();

I use the dictionary, because then I can have a unique key value and will be executed in the Dictionary.

The key value will be int. Before I needed only one value. Now everything has expanded to the point where I need to save several values ​​(with different data types) for the same key.

Something like this (although this will not work):

Dictionary<int,string,string,bool, bool,int,bool> d = new Dictionary<int, string,string,bool, bool,int,bool>();

Note that row, row, bool, bool, int, bool are additional values ​​that I like to store for the key field, which will be int.

I'm not sure how I will do this. How to get a key value for storing multiple values ​​with different data types. On the way by which I see that it is possible, you need to save additional fields in the list, but I'm not sure how it all comes. If someone can provide an example to be appreciated.

Thanks in advance.

+5
source share
4 answers

Create your own data type with fields string, string, bool, bool, int, booland use this as a dictionary value.

class MyType
{
    public string SomeVal1{ get; set; }
    public string SomeVal2{ get; set; }
    public bool SomeVal3{ get; set; }
    public bool SomeVal4{ get; set; }
    public int SomeVal5{ get; set; }
    public bool SomeVal6{ get; set; }
}

then

var someDictionary = new Dictionary<int, MyType>();

and

someDictionary.Add( 1, 
                    new MyType{
                        SomeVal1 = "foo",
                        SomeVal2 = "bar",
                        SomeVal3 = true,
                        SomeVal4 = false,
                        SomeVal5 = 42,
                        SomeVal6 = true
                    });
+16
source

You can use Tupleas a generic type for a value.

var d = new Dictionary<int,Tuple<string,string,bool, bool,int,bool>>();

Alternatively, create a type (class or structure) that contains different types as a group — this is most likely the best way to model things.

+11
source

, , , , , - , , .

0

- key / value. . , , , . :

var d = new Dictionary<int, string, string, bool, bool, int, bool>();

, . :

public class Person : IPerson
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public bool IsMarried { get; set; }
    public bool HasChildren { get; set; }        
    public bool IsHappy { get; set; }

    public Person(int id)
    {
        Id = id;
    }
}

Obviously, this object is completely created to match types and represent data in a container. With this understanding, you could do the following:

var d = new Dictionary<int, IPerson>();
0
source

All Articles