在添加新元组之前,我想检查列表是否已包含该元组并避免再次将其添加到列表中,我将如何执行此操作?我知道对于整数和字符串,您只需编写 list.Contains(2) 或 list.Contains("2"),但我不确定在检查元组时使用什么语法。
到目前为止我已经尝试过这两个(片段)。(组合是元组<char, char>的列表)
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));
}
Run Code Online (Sandbox Code Playgroud)
添加效果很好,所以我认为比较时会是相同的。任何有关语法或逻辑的帮助都会很棒,谢谢:)
元组已经实现了适当的相等性,因此除了创建值然后使用 之外,您不需要执行任何操作.Contains。然而:
ValueTuple<...>更喜欢Tuple<...>, 和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
Run Code Online (Sandbox Code Playgroud)
您还可以在此处命名部件:
// 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
Run Code Online (Sandbox Code Playgroud)
这将允许您通过编译器 voodoo使用.Xand on 值。.Y