0

I have a IEnumerable<> object which I am iterating using for loop as shown below:

IEnumerable<Process> dataHolder = GetData();
// how to write below foreach loop in one-liner?
foreach (var x in dataHolder)
{
    loggingService.Warn(LOG_TITLE, "Value: " + x.ClientName);
}

I was just curious to understand if there is any way I can write above foreach loop with logging line in one-liner.

cs98
  • 129
  • 2
  • 10
  • 2
    How about: `foreach (var x in dataHolder) loggingService.Warn(LOG_TITLE, "Value: " + x.ClientName);`? – Sweeper Aug 13 '20 at 06:19
  • sure that works too and that I already know that but is there any other way where we don't even have to write like that? – cs98 Aug 13 '20 at 06:20
  • 2
    what do you mean by "don´t have to write it like that"? What is your actual **goal**? Your code is pretty straight-forward and easy to understand. If course you can write your entire program within a single line, but **should** you? – MakePeaceGreatAgain Aug 13 '20 at 06:26
  • There is nothing wrong with the code you have, and is likely preferable over the `ForEach` extension method. Likely its better to just build a string with that log message, and log the one entry – TheGeneral Aug 13 '20 at 06:31

2 Answers2

7

List has a ForEach method, where it will call a supplied lambda on every one of its elements:

dataHolder.ToList().ForEach(x => loggingService.Warn(LOG_TITLE, "Value: " + x.ClientName));

It isn't really clear what you're asking, but this could be a way to "have code run on every item in a bunch of items, without using the word foreach (case sensitive)"

I'm not sure I'd use it though, because it requires an extra conversion step to List (ForEach is a List thing not a LINQ thing) when foreach will work just fine on the existing IEnumerable you have.. As such I would claim that using ForEach when you could foreach for code-presentation reasons is a fine use case for one of my favorite memes:

enter image description here

ps; this question has some wonderful and lengthy discourse on the differences and when it might be better to use one over the other. As your stated goal doesn't encompass any of the finer points of mutating state, thread safety etc I'd stick with foreach

Caius Jard
  • 72,509
  • 5
  • 49
  • 80
0

Although you wanted a one liner, I think it's better to add all the information to just one log message

var results = GetData().Select(x => "Value: " + x.ClientName);
loggingService.Warn(LOG_TITLE, string.Join(Environemnt.NewLine, results));

You could use comma separated if you don't like new lines.

Note : These days I tend to use more modern structured logging frameworks where you would include the data as a list/structure.

halfer
  • 19,824
  • 17
  • 99
  • 186
TheGeneral
  • 79,002
  • 9
  • 103
  • 141