This is purely to simplify the code and make it more readable.
I print out a list of Windows Services on my computer. In doing so, I call the ServiceController.GetServices() and retrieve an array of the services. But I would prefer to get it in a strongly typed list and print it out to my txbMain text box. I have managed to both of these things in 3 lines of code. But is there a way to print out to txbMain in the first line so I can avoid the foreach loop?
List<ServiceController> list = ServiceController.GetServices()
.OrderBy(x => x.DisplayName)
.ToList();
foreach (ServiceController sc in list)
txbMain.Text += sc.DisplayName + Environment.NewLine;
If you don’t use your list after this statement, you can do :
Note that it will internally perform a foreach loop anyway.
Worse, it will first have to create a list before using the ForEach method, which is time consuming.
See Eric Lippert’s post about it.
Maybe you should stick with your foreach loop.