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

Time:12-06

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 :)

CodePudding user response:

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");
}

CodePudding user response:

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.

CodePudding user response:

Here is your solution

List<Tuple<char, char>> combinations = new() {
             new Tuple<char, char>('A', 'B'),
             new Tuple<char, char>('C', 'D'),
             new Tuple<char, char>('E', 'F')
             };

// 
var t1 = new Tuple<char, char>('A', 'B');
//you can perform ||(OR) or &&(AND) in between item1 and item2
bool isExist = combinations.Any(x => x.Item1 == t1.Item1 || x.Item2 == t1.Item2); 

Any is a linq extension method supporting docs

  • Related