是否有像List (多维通用列表)

是否有像List <String,Int32,Int32>(多维通用列表)

问题描述:

我需要类似于List<String, Int32, Int32>。列表一次只支持一种类型,而一次只有两种字典。有没有一种干净的方式来做类似上面的事情(一个多维的通用列表/集合)?是否有像List <String,Int32,Int32>(多维通用列表)

+0

Int32的重复很有趣。你想做什么? – 2010-06-08 04:53:44

+0

我必须用一个字符串在语义上关联两个不同的数字,然后用它来在视图中呈现数据。 – Alex 2010-06-08 04:56:37

+0

我认为@Alex有像我这样的'java'背景。 – 2013-07-16 07:33:04

最好的办法是为它创建一个容器,即一类

public class Container 
{ 
    public int int1 { get; set; } 
    public int int2 { get; set; } 
    public string string1 { get; set; } 
} 

然后在你需要它

List<Container> myContainer = new List<Container>(); 
+4

+1,因为它不需要.Net4元组,并且可以使用类实现轻微实现,但是-1,因为您应该避免在类上使用公共字段。实现为一个属性并使用简单的'{get;设置;}'而不是。 – 2010-06-08 05:01:08

+0

您可能需要重写Equals和GetHashCode – 2010-06-08 05:08:26

+1

类型Container应该是不可变的结构体,因为它只代表值。 – 2010-06-08 05:10:25

在.NET 4中,您可以使用List<Tuple<String, Int32, Int32>>

+0

不幸的是我在.NET 3.5上,但我会记住4.0! – Alex 2010-06-08 04:57:19

好代码,你不能这样做直到C#3.0,如果您可以像其他答案中提到的那样使用C#4.0,请使用元组。

但是在C#3.0中创建Immutable structure并在结构中包装所有类型的insities,并将结构类型作为泛型类型参数传递给列表。

public struct Container 
{ 
    public string String1 { get; private set; } 
    public int Int1 { get; private set; } 
    public int Int2 { get; private set; } 

    public Container(string string1, int int1, int int2) 
     : this() 
    { 
     this.String1 = string1; 
     this.Int1 = int1; 
     this.Int2 = int2; 
    } 
} 

//Client code 
IList<Container> myList = new List<Container>(); 
myList.Add(new Container("hello world", 10, 12)); 

如果您好奇为什么要创建不可变的结构 - checkout here

根据你的评论,这听起来像你需要一个带有字符串键的字典中存储的两个整数的结构。

struct MyStruct 
{ 
    int MyFirstInt; 
    int MySecondInt; 
} 

... 

Dictionary<string, MyStruct> dictionary = ... 
+0

这是假设字符串是唯一的。 – 2010-06-08 05:03:57