Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if list of Tuple contains a tuple where Item1 = x using Linq

Tags:

c#

list

linq

tuples

I have a list of products, but I want to simplify it into a tuple since I only need the productId and brandId from each product. Then in later code would like to check if the list of tuple contains a tuple where Item1 = x, and in a separate case where Item2 = y.

List<Tuple<int, int>> myTuple = new List<Tuple<int, int>>();

foreach (Product p in userProducts)
{
    myTuple.Add(new Tuple<int, int>(p.Id, p.BrandId));
}

int productId = 55;
bool tupleHasProduct = // Check if list contains a tuple where Item1 == 5
like image 881
Blake Rivell Avatar asked Feb 20 '16 16:02

Blake Rivell


2 Answers

In Linq, you can use the Any method to check for existence of a condition evaluating to true:

bool tupleHadProduct = userProducts.Any(m => m.Item1 == 5);

See also: https://msdn.microsoft.com/library/bb534972(v=vs.100).aspx

like image 60
Jason W Avatar answered Oct 19 '22 06:10

Jason W


In the code that you show it's not really necessary to use a tuple:

    // version 1
    var projection = from p in userProducts
                     select new { p.ProductId, p.BrandId };

    // version 2
    var projection = userProducts.Select(p => new { p.ProductId, p.BrandId });

    // version 3, for if you really want a Tuple
    var tuples = from p in userProducts
                 select new Tuple<int, int>(p.ProductId, p.BrandId);

    // in case of projection (version 1 or 2):
    var filteredProducts = projection.Any(t => t.ProductId == 5);

    // in case of the use of tuple (version 3):
    var filteredTuples = tuples.Any(t=>t.Item1 == 5);
like image 29
Pascal Naber Avatar answered Oct 19 '22 06:10

Pascal Naber