使用 Linq 检查元组列表中是否包含 Item1 = x 的元组

13

我有一个产品清单,但我只需要每个产品的productId和brandId,想将其简化为元组。然后在后续的代码中,我想检查元组列表是否包含其中Item1 = x的元组,并在另一种情况下,检查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
2个回答

34

适用于 List<(int Product, int Brand)> 吗? - Kiquenet

3
在您展示的代码中,使用元组并不是必须的。
    // 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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接