2010-06-08 69 views
7

我需要類似於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

回答

14

最好的辦法是爲它創建一個容器,即一類

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

13

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

+0

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

1

好代碼,你不能這樣做直到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

0

根據你的評論,這聽起來像你需要一個帶有字符串鍵的字典中存儲的兩個整數的結構。

struct MyStruct 
{ 
    int MyFirstInt; 
    int MySecondInt; 
} 

... 

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

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

相關問題