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
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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With