LINQ return items in a List that matches any Names (string) in another list

前端 未结 5 1281
故里飘歌
故里飘歌 2020-12-08 00:46

I have 2 lists. 1 is a collection of products. And the other is a collection of products in a shop.

I need to be able to return all shopProducts if the names match a

相关标签:
5条回答
  • 2020-12-08 01:08

    You could create an IEqualityComparer<T> that says products with equal names are equal.

    class ProductNameEqulity : IEqualityComparer<Product>
    {
        public bool Equals(Product p1, Product p2)
        {
            return p1.Name == p2.Name
        }
    
        public int GetHashCode(Product product)
        {
            return product.Name.GetHashCode();
        }
    }
    

    Then you can use this in the Intersect extension method.

    var products = shopProducts.Intersect(listOfProducts, new ProductNameEquality());
    
    0 讨论(0)
  • 2020-12-08 01:15
    var products = shopProducts
            .Where(shopProduct =>
                    listOfProducts.Any(p => shopProduct.Name == p.Name))
            .ToList();
    
    0 讨论(0)
  • 2020-12-08 01:17

    You could use a join, for example:

    var q = from sp in shopProducts
            join p in listOfProducts on sp.Name equals p.Name
            select sp;
    

    A fuller guide on join is here.

    0 讨论(0)
  • 2020-12-08 01:20

    Try this please

    var products  = shopProducts.Where(m=> listOfProducts.Select(l=>l.Name).ToList().Contains(m=>m.Name));
    
    0 讨论(0)
  • 2020-12-08 01:29
    var products = shopProducts.Where(p => listOfProducts.Any(l => p.Name == l.Name))
                               .ToList();
    

    For LINQ-to-Objects, if listOfProducts contains many items then you might get better performance if you create a HashSet<T> containing all the required names and then use that in your query. HashSet<T> has O(1) lookup performance compared to O(n) for an arbitrary IEnumerable<T>.

    var names = new HashSet<string>(listOfProducts.Select(p => p.Name));
    var products = shopProducts.Where(p => names.Contains(p.Name))
                               .ToList();
    

    For LINQ-to-SQL, I would expect (hope?) that the provider could optimise the generated SQL automatically without needing any manual tweaking of the query.

    0 讨论(0)
提交回复
热议问题