如何在C#中检查列表是否包含元组

3

在添加新元组之前,我希望检查列表是否已经包含该元组并避免重复添加到列表中,我该如何实现?对于整数和字符串,您可以编写list.Contains(2)或list.Contains("2"),但是我不确定在检查元组时要使用什么语法。

我尝试了以下两个片段(组合是一个元组<char,char>的列表)

if ('a', 'b') not in combination:
    combination.append(('a', 'b'))
    
if not any(c[0] == 'a' and c[1] == 'b' for c in combination):
    combination.append(('a', 'b'))
if(!combinations.Contains(Tuple<char, char>(s[i], chr)))
{
    combinations.Add(new Tuple<char, char>(s[i], chr));
}
                    
if(!combinations.Contains(Tuple<char, char> s[i], chr))
{
    combinations.Add(new Tuple<char, char>(s[i], chr));
}

添加功能正常,所以我认为比较也应该是一样的。对于语法或逻辑方面的任何帮助都将是非常好的,谢谢:)


2
你可以使用 .Contains(Tuple.Create(s[i], chr))。另外:如果你的 combinations 是一个 List<Tuple<char, char>>,并且你不想要重复项,也许你应该使用 HashSet<Tuple<char, char>>?它的 Add 方法会在集合中已经存在该项时什么都不做。 - Jeppe Stig Nielsen
我假设你想知道元组的值是否与列表中已有的值相同?而不是实际上是相同的元组(相同的内存地址)? - Peter
2个回答

6

元组已经实现了适当的相等性,所以除了创建值和使用 .Contains 之外,您不需要做任何事情。但是:

  1. 您可能更喜欢使用 ValueTuple<...> 而不是 Tuple<...>,并且
  2. 如果顺序不重要,您可能更喜欢使用 HashSet<T>,它可以在内部处理唯一性

例如:

// note that (char, char) is a ValueTuple<char, char>
private readonly HashSet<(char,char)> combinations = new();
//...
combinations.Add((x, y)); // adds the x/y tuple if it doesn't exist

您也可以在此处给这些部件命名:

private readonly HashSet<(char X,char Y)> combinations = new();

通过编译器技巧,您可以使用 .X.Y 来处理值。


4
在C#中,您可以使用Contains()方法来检查列表是否包含特定的元组。以下是一个示例:
// List of tuples
var tupleList = new List<(char, char)>()
{
    ('a', 'b'),
    ('c', 'd'),
    ('e', 'f')
};

// Tuple to search for
var searchTuple = ('a', 'b');

// Check if the list contains the tuple
if (tupleList.Contains(searchTuple))
{
    Console.WriteLine("The list contains the tuple");
}
else
{
    Console.WriteLine("The list does not contain the tuple");
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接