tags:

views:

198

answers:

6

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?

+16  A: 

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...

Jon Skeet
Ooh tuple ....!
James Westgate
Sealed, readonly, properties, ... - don't confuse him ;)
Danvil
Sealed, readonly, properties, ... - one of the most concise immutable examples I've seen. But what about overriding Equals and GetHashCode? :)
Jesse C. Slicer
+6  A: 
class A {
  public string X, Y;
}

Dictionary<string, A> data;
Danvil
+3  A: 

Create a struct containing your values and then use

Dictionary<string, MyStruct> dict = new Dictionary<string, MyStruct>();
Oskar Kjellin
A: 

You can use a dictionary of KeyValuePairs

Dictionary<string,KeyValuePair<string,string>>
digEmAll
I don't like this idea, as although it *will* do what you want, it's misleading - why is the second string viewed as a key for the third?
Jon Skeet
Yes, you're right, but in some situations that is a fast and not so ugly solution...Anyway a custom implementation, or the use of Tuple is probably the best in general (but Tuple is only in .net 4.0)
digEmAll
-1 This is very misleading. There is no logic in what should be a key and what should be a value in the KeyValuePair<string,string>
Oskar Kjellin
A: 

Yes, there is exactly that. You can store your two values in a class or a structure. Or do you want something else?

IVlad
A: 

Make a class to hold your value and make it a Dictionary. If the class is only used in the context of one containing class (e.g. it is used to deliver a data structure for a class property), you can make your class a private nested class.

Tom Cabanski