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

C# 使用Linq检查元组列表是否包含Item1=x的元组,c#,linq,list,tuples,C#,Linq,List,Tuples,我有一个产品列表,但我想将其简化为一个元组,因为我只需要每个产品的productId和brandId。然后,在后面的代码中,我们将检查元组列表是否包含Item1=x的元组,以及在单独的情况下Item2=y的元组 List<Tuple<int, int>> myTuple = new List<Tuple<int, int>>(); foreach (Product p in userProducts) { myTuple.Add(new

我有一个产品列表,但我想将其简化为一个元组,因为我只需要每个产品的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
List myTuple=new List();
foreach(userProducts中的产品p)
{
添加(新元组(p.Id,p.BrandId));
}
int productId=55;
bool tupleHasProduct=//检查列表是否包含Item1==5的元组

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

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

另请参见:

在您展示的代码中,实际上不需要使用元组:

    // 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);
//版本1
var projection=从用户产品中的p开始
选择新的{p.ProductId,p.BrandId};
//版本2
var projection=userProducts.Select(p=>new{p.ProductId,p.BrandId});
//版本3,如果你真的想要一个元组
var tuples=来自userProducts中的p
选择新元组(p.ProductId,p.BrandId);
//如果是投影(版本1或版本2):
var filteredProducts=projection.Any(t=>t.ProductId==5);
//如果使用元组(版本3):
var filteredTuples=tuples.Any(t=>t.Item1==5);