带有 2 个参数的列表
List with 2 arguments
我目前有这个代码:
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
有没有可能我可以实现类似的东西?
您可以使用 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
如果你有一个键值对,你也可以使用字典:
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);
}
您似乎在尝试像矩阵一样使用列表。在那种情况下,您可能会发现 Math.NET 有用。
我目前有这个代码:
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
有没有可能我可以实现类似的东西?
您可以使用 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
如果你有一个键值对,你也可以使用字典:
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);
}
您似乎在尝试像矩阵一样使用列表。在那种情况下,您可能会发现 Math.NET 有用。