List.ForEach

  • Thread starter Thread starter Kevin G
  • Start date Start date
K

Kevin G

Hi. I'm trying to prepare an example on how to use List.ForEach.

using the regular ForEach, I can get what I want with the folllowing
code:

List<string> lAvailablePorts = new List<string>();
lAvailablePorts.AddRange(SerialPort.GetPortNames());

string sPortsAvailable = "";
foreach (string sPort in lAvailablePorts)
{
sPortsAvailable += " " + sPort;
}

this.LogThis("Ports Available: " + sPortsAvailable);

however, I think I can do it like this:

List<string> lAvailablePorts = new List<string>();
lAvailablePorts.AddRange(SerialPort.GetPortNames());

this.LogThis("Ports Available: " + lAvailablePorts.ForEach(What
Do I put Here?));

can anyone help me out with the syntax?


-K
 
The delegate in the ForEach method doesn't have a return value, so you
still need a variable to collect them.

A StringBuilder is better than concatenating strings, unless you are
absolutely sure that the number or items are always very low, and even
then, a StringBuilder is quite convenient.

List<string> ports;
StringBuilder available;

ports = new List<string>();
ports.AddRange(SerialPort.GetPortNames());
available = new StringBuilder();
ports.ForEach(delegate(string port) { available.Append("
").Append(port); } );
this.LogThis("Ports Available: " + available.ToString());
 
Back
Top