列出2个参数

And*_*ics 5 c# int arguments arraylist

我目前正在使用此代码:

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];
Run Code Online (Sandbox Code Playgroud)

有没有一种可能的方法,此列表可以在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
Run Code Online (Sandbox Code Playgroud)

我有可能实现类似的目标吗?

Fla*_*ric 5

您可以使用Tuple

var list = new List<Tuple<int, int>>();
list.Add(new Tuple<int, int>(1, 2));
Run Code Online (Sandbox Code Playgroud)

为了便于使用,您可以创建扩展方法:

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));
    }
}
Run Code Online (Sandbox Code Playgroud)

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

list.Add(1, 2);
Run Code Online (Sandbox Code Playgroud)

要访问这些项目:

var listItem = list[0]; // first item of list
int value = listItem.Item2; // second "column" of the item
Run Code Online (Sandbox Code Playgroud)