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 exam开发者_如何学Cple:
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
GlobalStrings.AddRange(localStrings);
Note: You cannot declare the list object using the interface (IList).
Documentation: List<T>.AddRange(IEnumerable<T>)
.
GlobalStrings.AddRange(localStrings);
That works.
Documentation: List<T>.AddRange(IEnumerable<T>)
.
Try AddRange-method:
GlobalStrings.AddRange(localStrings);
With Linq
var newList = GlobalStrings.Append(localStrings)
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);
}
if you want to get "terse" :)
List<string>GlobalStrings = new List<string>();
for(int x=1; x<10; x++) GlobalStrings.AddRange(new List<string> { "some value", "another value"});
if you want to get "terse" :)
GlobalStrings.AddRange(localStrings);
精彩评论