Append a Lists Contents to another List C#
I have the following:
- A main List called GlobalStrings
- Another List called localStrings
In a loop for example:
List<string> GlobalStrings = new List<string>();
List<string> localStrings = new List<string>();
for(x=1;x<10;x++)
{
localStrings.Add("some value");
localStrings.Add("some value");
}
// Want to append localStrings to GlobalStrings as easily as possible
Solution 1:
GlobalStrings.AddRange(localStrings);
Note: You cannot declare the list object using the interface (IList).
Documentation: List<T>.AddRange(IEnumerable<T>)
.
Solution 2:
GlobalStrings.AddRange(localStrings);
That works.
Documentation: List<T>.AddRange(IEnumerable<T>)
.
Solution 3:
Try AddRange-method:
GlobalStrings.AddRange(localStrings);
Solution 4:
With Linq
var newList = GlobalStrings.Append(localStrings)
Solution 5:
Here is my example:
private List<int> m_machinePorts = new List<int>();
public List<int> machinePorts
{
get { return m_machinePorts; }
}
Init()
{
// Custom function to get available ethernet ports
List<int> localEnetPorts = _Globals.GetAvailableEthernetPorts();
// Custome function to get available serial ports
List<int> localPorts = _Globals.GetAvailableSerialPorts();
// Build Available port list
m_machinePorts.AddRange(localEnetPorts);
m_machinePorts.AddRange(localPorts);
}