【问题标题】:List with 2 arguments带有 2 个参数的列表
【发布时间】:2015-10-24 02:02:13
【问题描述】:

我目前有这个代码:

List<int> list = new List<int>();
list.Add(0);
list.Add(1);
list.Add(2);
list.Add(3);
color0 = list[1];
color1 = list[2];
color2 = list[3];
color3 = list[4];

有没有可能的方法,这个列表可以在 1 个元素中包含 2 个参数?我的意思是:

List<int,int> list = new List<int,int>();
list.Add(0,3);
list.Add(1,8);
color0=list[1][2]; //output 3
color1=list[1][1]; //output 0
color2=list[2][2]; //output 8
color3=list[2][1]; //output 1

有没有可能我可以实现类似的东西?

【问题讨论】:

    标签: c# arraylist int arguments


    【解决方案1】:

    你可以使用Tuple:

    var list = new List<Tuple<int, int>>();
    list.Add(new Tuple<int, int>(1, 2));
    

    为了方便使用,你可以创建一个扩展方法:

    public static class Extensions
    {
        public static void Add(this List<Tuple<int, int>> list, int x, int y)
        {
            list.Add(new Tuple<int, int>(x, y));
        }
    }
    

    然后您可以使用以下代码添加元素:

    list.Add(1, 2);
    

    访问项目:

    var listItem = list[0]; // first item of list
    int value = listItem.Item2; // second "column" of the item
    

    【讨论】:

    • ..并以color3 = list[7].Item1;访问它
    【解决方案2】:

    看起来您正在尝试使用矩阵之类的列表。在这种情况下,您可能会发现 Math.NET 很有用。

    【讨论】:

      【解决方案3】:

      如果你有一个键值对,你也可以使用字典:

      static void Main()
          {
          Dictionary<int, int> dictionary =
              new Dictionary<int, int>();
      
          dictionary.Add(0,3);
          dictionary.Add(1,8);
          dictionary.Add(2, 13);
          dictionary.Add(3, -1);
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-02-12
        • 1970-01-01
        • 2018-10-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多