Reputation: 33
Before adding a new tuple, I want to check if a list already contains that tuple and avoiding adding it to the list again, how would I got about doing this? I'm aware for integers and strings you would just write list.Contains(2) or list.Contains("2"), but i'm not sure what syntax to use when checking for tuples.
I've tried these two so far (snippets). (combination is a list of tuples<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));
}
Adding works fine so I thought it would be the same when comparing. Any help with syntax or logic would be great, thanks :)
Upvotes: 3
Views: 1594
Reputation: 1062550
Tuples already implement the appropriate equality, so you shouldn't need to do anything except create the value, and then use .Contains
. However:
ValueTuple<...>
over Tuple<...>
, andHashSet<T>
, which handles uniqueness internallyFor example:
// 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
You can also name the parts here:
private readonly HashSet<(char X,char Y)> combinations = new();
which will allow you to use .X
and .Y
on values, via compiler voodoo.
Upvotes: 6
Reputation: 153
In C#, you can use the Contains() method to check if a list contains a specific tuple. Here is an example:
// 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");
}
Upvotes: 4