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

时间:2016-02-20 16:17:20

标签: 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 Tuple<int, int>(p.Id, p.BrandId));
}

int productId = 55;
bool tupleHasProduct = // Check if list contains a tuple where Item1 == 5

2 个答案:

答案 0 :(得分:9)

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

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

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

答案 1 :(得分:2)

在你展示的代码中,没有必要使用元组:

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