16

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?

4

4 回答 4

25

字典是一个键值对,其中的值是根据键获取的。键都是唯一的。

现在,如果您想要一个Dictionary具有 1 个键类型和多个值类型的,您有几个选择:

首先是使用一个Tuple

var dict = new Dictionary<KeyType, Tuple<string, string, bool, int>>()

另一种是使用(使用 C# 4.0 及更高版本):

var dict = new Dictionary<KeyType, dynamic>()

System.Dynamic.ExpandoObject可以具有任何类型的值。

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);
   }
}
于 2013-02-20T18:35:51.813 回答
6

用类描述适当的键字段和适当的值字段并使用这些类型的字典。

var dictionary = new Dictionary<TheKeyType, TheValuesType>();

注意:如果您有多个值作为键,您将定义一个类来封装这些值并提供对 GetHashCode 和 Equals 的适当覆盖,以便字典可以识别它们的相等性。

如果不这样做,您可以使用元组,但您想限制这种模式,因为元组是非自描述的。

var dictionary = new Dictionary<Tuple<Key1Type, Key2Type, Etc>, Tuple<Value1Type, Value2Type, Etc>>();
于 2013-02-20T18:25:34.267 回答
3

我建议不要使用元组,这是一个完全有效的解决方案,而是创建自己的类作为键和/或值。

您可能会意识到元组将成为难以阅读的代码。

于 2013-02-20T18:26:28.960 回答
0

使用元组作为键。

var d = new Dictionary<Tuple<string,string,bool,int>,any-data-typs>();
于 2013-02-20T18:24:40.500 回答