-2
 var coupon=" ";

 foreach(var p in products)
 {
     var query = products.Where(b => b.getId() == p.getId()).ToList();

     if (query != null)
     {
         foreach(var q in query)
         {
             coupon = q.getName();
             Console.WriteLine(coupon);
         }
     }
 }

Can anyone tell me what will be the lambda expression of this code-chunk

ggorlen
  • 44,755
  • 7
  • 76
  • 106
Piku
  • 19
  • 1
  • 2
  • Your question is completely unclear. For which part of this code you need an expression? Anyway this question is far too broad, in particlar as you didn´t provide *any* own affords. We´re not here to do your job. – MakePeaceGreatAgain Sep 05 '18 at 19:27

2 Answers2

4

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);
     }
 }
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • For each product `p`, it writes out the coupon name of all products `q` that share the ID with `p` (including `p` itself). I wonder what ID that is. I agree with your statement _Not every loop operation is a natural fit for a lambda expresssion._ However, if we wanted to create an `IEnumerable<>` of all those coupon names, instead of `Console.WriteLine`, then it might fall under the category of projections of data... – Jeppe Stig Nielsen Sep 05 '18 at 20:47
0

There is a lambda expression in your code block and it is the only argument to Where and is as follows:

b => b.getId() == p.getId()

In this particular case, the lambda is effectively (though not technically) a Predicate, which is a fancy name for a function that tests if something is true or false

John Cummings
  • 1,949
  • 3
  • 22
  • 38
  • 1
    Technically, the argument required by `.Select` is a `Func`, not a `Predicate` like in .NET-2.0-style methods such as `List<>.FindAll(…)`, however `Func` and `Predicate` are equivalent (same signature and return type). – Jeppe Stig Nielsen Sep 05 '18 at 20:53
  • Good point, I have updated my answer with that clarification. – John Cummings Sep 05 '18 at 21:20