将列表内容附加到另一个列表 C#

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1825568/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 21:09:48  来源:igfitidea点击:

Append a Lists Contents to another List C#

c#

提问by JL.

I have the following:

我有以下几点:

  1. A main List called GlobalStrings
  2. Another List called localStrings
  1. 一个名为 GlobalStrings 的主列表
  2. 另一个名为 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

采纳答案by Lee

GlobalStrings.AddRange(localStrings);

Note: You cannot declare the list object using the interface (IList).
Documentation: List<T>.AddRange(IEnumerable<T>).

注意:您不能使用接口 (IList) 声明列表对象。
文档:List<T>.AddRange(IEnumerable<T>).

回答by Blake Pettersson

With Linq

与林克

var newList = GlobalStrings.Append(localStrings)

回答by Jimmeh

GlobalStrings.AddRange(localStrings);

That works.

那个有效。

Documentation: List<T>.AddRange(IEnumerable<T>).

文档:List<T>.AddRange(IEnumerable<T>).

回答by martin

Try AddRange-method:

尝试 AddRange 方法:

GlobalStrings.AddRange(localStrings);

回答by BillW

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"});

回答by Jim Lahman

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);
     }