Contains half a tuple

Viewed 54

How can I check if a list contains a tuple partial match?

var tuples = new List<(int, int)>( new [] { (1, 1), (1, 2), (3, 4), (4, 2) } );
tuples.Contains((3, _));
3 Answers

Using Linq:

var tuples = new List<(int, int)>(new[] { (1, 1), (1, 2), (3, 4), (4, 2) });
if (tuples.Any(x => x.Item1 == 3))
{
   //....
}

You can use the pattern matching is operator, which is very close to the syntax you had in mind:

tuples.Any(x => x is (3, _));

You could write a custom Contains function, but a .Where will work just fine:

using System.Linq;
[...]

tuples.Where(tup => tup.Item1 == 3);
Related