Not every loop operation is a natural fit for a lambda expresssion. Lambda expressions are useful for projections of data - i.e. transforming it from one form to another - applying formulae etc, but: that isn't what you're doing here. You're doing something with the data (the Console.WriteLine
. You could do something with LINQ here involving SelectMany
, but... it would become less readable, not more.
What you have alread is just fine. The only changes I'd make are:
- to remove the
if (query != null)
test - that is never going to be false
- remove the
ToList()
- there's no need to create a new list just to iterate it
- no need to declare
coupon
before it is needed
- I might hoist the
p.getId()
So:
foreach(var p in products)
{
var id = p.getID();
foreach(var q in products.Where(b => b.getId() == id))
{
var coupon = q.getName();
Console.WriteLine(coupon);
}
}