Checking if list of Tuple contains a tuple where Item1 = x using Linq
21,469
Solution 1
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
Solution 2
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);
Author by
Blake Rivell
I am a .NET developer who builds custom web applications for businesses. I have a very strong passion for what I do. My hobbies are video games and fitness.
Updated on July 09, 2022Comments
-
Blake Rivell almost 2 years
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