How do I check if a list contains a tuple in C#

How do I check if a list contains a tuple in C#

Problem Description:

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 🙂

Solution – 1

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");
    Console.WriteLine("The list does not contain the tuple");

Solution – 2

Tuples already implement the appropriate equality, so you shouldn’t need to do anything except create the value, and then use .Contains. However:

  1. you may prefer ValueTuple<...> over Tuple<...>, and
  2. if order doesn’t matter, you may prefer HashSet<T>, which handles uniqueness internally

For 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.

Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.