有类似于 List<String, Int32, Int32>(多维泛型列表)的东西吗?

7

我需要类似于 List<String, Int32, Int32> 的东西。List只支持一种类型,而Dictionary只支持两种类型。是否有一种干净的方式来做类似上面这样的事情(多维泛型列表/集合)?


Int32的复制很有趣。你想要做什么? - Austin Salonen
我必须将两个不同的数字语义化地与一个字符串关联起来,然后在视图中使用该字符串来呈现数据。 - Alex
我认为@Alex和我一样有Java编程背景。 - Davut Gürbüz
4个回答

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; set;} 代替。 - Robert Paulson
您可能还需要重写 Equals 和 GetHashCode 方法。 - Rohan West
1
类型 Container 应该是一个不可变的结构体,因为它仅表示值。 - this. __curious_geek
1
根据Alex的实现需求,他可以决定是否需要一个Equals to,并且可以根据他项目的需求决定Class Vs Struct。然而,如果仅用于存储值,那么使用Struct会更合理。 - Jason Jong

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

很不幸,我正在使用.NET 3.5,但是我会记住这个对于4.0的! - Alex

1

嗯,你不能在C# 3.0之前这样做,如果你可以使用C# 4.0,就像其他答案中提到的那样,使用元组。

但是在C# 3.0中 - 创建一个不可变结构,并将所有类型的实例包装在结构中,并将结构类型作为泛型类型参数传递给列表。

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));

如果你好奇为什么要创建不可变的结构体 - 在这里查看


0
根据您的评论,似乎您需要一个包含两个整数的结构体,并将其存储在一个带有字符串键的字典中。
struct MyStruct
{
   int MyFirstInt;
   int MySecondInt;
}

...

Dictionary<string, MyStruct> dictionary = ...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接