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

本文关键字:元组 Item1 包含 是否 Linq 检查 列表 使用 | 更新日期: 2023-09-27 18:35:27

我有一个产品列表,但我想将其简化为元组,因为我只需要每个产品的产品 Id 和品牌 Id。然后在后面的代码中,想要检查元组列表是否包含一个元组,其中 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

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

在 Linq 中,可以使用 Any 方法检查是否存在计算结果为 true 的条件:

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

另请参阅:https://msdn.microsoft.com/library/bb534972(v=vs.100).aspx

在您显示的代码中,实际上没有必要使用元组:

    // 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);