Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Dictionary, 2 Values

Tags:

c#

dictionary

What would be the best C# data structure for using one key, and having two values pulled out?

Essentially I need a Dictionary<string, string, string>. Is there something like this?

like image 448
cam Avatar asked Apr 19 '10 14:04

cam


1 Answers

If you're using .NET 4, you could use

Dictionary<string, Tuple<string, string>>

If you're not, you could create your own Tuple type which works the same way :)

Alternatively, if you only need this in one place you could create your own type which encapsulated the two strings neatly using appropriate names. For example:

public sealed class NameAndAddress
{
    private readonly string name;
    public string Name { get { return name; } }

    private readonly string address;
    public string Address { get { return address; } }

    public NameAndAddress(string name, string address)
    {
        this.name = name;
        this.address = address;
    }
}

Then you can use:

Dictionary<string, NameAndAddress>

which makes it very clear what's going to be stored.

You could implement equality etc if you wanted to. Personally I would like to see this sort of thing made easier - anonymous types nearly do it, but then you can't name them...

like image 51
Jon Skeet Avatar answered Sep 24 '22 13:09

Jon Skeet