问题描述
我想添加到声明为的元组的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));