开发者

C# Dictionary, 2 Values

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开发者_如何学Go>. Is there something like this?


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


class A {
  public string X, Y;
}

Dictionary<string, A> data;


Create a struct containing your values and then use

Dictionary<string, MyStruct> dict = new Dictionary<string, MyStruct>();


You can use a dictionary of KeyValuePairs

Dictionary<string,KeyValuePair<string,string>>


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜