-4

Just started with Lambda in c# and I got stumbled by this.How can I convert following code block to lambda expression, adding all the values in headers get added to DefaultRequestHeaders.

var client = new HttpClient();
foreach (var header in headers)
{
    client.DefaultRequestHeaders.Add(header.Name, header.Value);
} 
stuartd
  • 70,509
  • 14
  • 132
  • 163
Gautam
  • 363
  • 1
  • 4
  • 15
  • 2
    I think you'll find a similar question here: https://stackoverflow.com/questions/1509442/linq-style-for-each – MikeS May 25 '18 at 17:21
  • 7
    I think you're referring to LINQ. This is not a case where I would use LINQ. LINQ is typically used for query operations (it's in the name!). Your loop doesn't match that usage. Additionally, your loop is already very straight forward and easy to read. LINQifying it would make it less clear. – itsme86 May 25 '18 at 17:22

1 Answers1

-1

This is no use case for a Lambda expression (as the discussion on Sim's answer shows), but it could be if you wanted to leverage parallel processing:

using System.Threading.Tasks;

Parallel.ForEach(headers, header => 
    client.DefaultRequestHeaders.Add(header.Key, header.Value)
);

I wouldn't do that in this case though. The class might not be thread-safe and there is nothing to be gained here in terms of performance.