【问题标题】:Is there something like List<String, Int32, Int32> (multidimensional generic list)是否有类似 List<String, Int32, Int32> (多维通用列表)的东西
【发布时间】:2010-06-08 04:48:09
【问题描述】:

我需要类似于List&lt;String, Int32, Int32&gt; 的东西。 List 一次只支持一种类型,而 Dictionary 一次只支持两种。有没有一种干净的方法来做类似上述的事情(多维通用列表/集合)?

【问题讨论】:

  • Int32 的重复很有趣。你想做什么?
  • 我必须在语义上将两个不同的数字与一个字符串相关联,然后将其用于在视图中呈现数据。
  • 我认为@Alex 有java 像我这样的背景。

标签: c# list collections generic-list


【解决方案1】:

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

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

然后在你需要的代码中

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

【讨论】:

  • +1 因为它不需要 .Net4 元组并且可以用类轻松实现,但是 -1 因为您应该避免类上的公共字段。实现为属性并改用简单的{get; set;}
  • 您可能还需要覆盖 Equals 和 GetHashCode
  • type Container 应该是一个不可变结构,因为它只表示值。
  • 根据 Alex 的实现需求,他可以决定是否需要 Equals,也可以决定 Class Vs Struct,同样取决于他的项目需要,但如果只是用于存储值,那么结构就有意义了。
【解决方案2】:

在 .NET 4 中,您可以使用 List&lt;Tuple&lt;String, Int32, Int32&gt;&gt;

【讨论】:

  • 不幸的是,我使用的是 .NET 3.5,但我会在 4.0 中记住这一点!
【解决方案3】:

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

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

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

【讨论】:

    【解决方案4】:

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

    struct MyStruct
    {
       int MyFirstInt;
       int MySecondInt;
    }
    
    ...
    
    Dictionary<string, MyStruct> dictionary = ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-25
      相关资源
      最近更新 更多