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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…