在C#中动态创建元组列表

问题描述

我想添加到声明为的元组的C#列表中

var myList = List<(int,int)>(); 

我该怎么做? Add方法{em>不接受 2 自变量。该代码for循环中计算 2 个整数。我想在每个循环中检查生成 2 个整数是否已经存在于myList中,如果不存在,请将其添加myList中。

解决方法

“添加方法不接受2个参数”

正确,但是您可以将Tuple<int,int>作为单个参数传递给列表,因为这是列表包含的类型。

“代码在for循环中计算2个整数。我想在每个循环中检查生成的2个整数是否已存在于myList中,如果不存在,则将其添加到myList中”。

某些代码在这里会有所帮助,但我建议从两个整数创建一个Tuple<int,int>,然后检查该元组是否已存在于列表中(Tuple覆盖Equals将其项目的值与其他Tuple中的项目进行比较,因此无需执行其他工作):

// We have two computed integers
int first = 5;
int second = 8;

// Add them as a Tuple to the list if it doesn't already exist
if (!myList.Contains((first,second))) myList.Add((first,second));