将值附加到列表

时间:2011-04-15 11:06:08

标签: c# .net collections

有没有办法在不使用循环的情况下将数字列表添加到List<int>

我的情景:

List<int> test = CallAMethod();   // It will return a List with values 1,2

test = CallAMethod();             // It will return a List with values 6,8

但现在第二组值将取代第一组。有没有办法在没有for循环的情况下将值附加到列表中?

3 个答案:

答案 0 :(得分:3)

List.AddRange Method

您需要执行以下操作:

lst.AddRange(callmethod());

或者,C#3.0,只需使用 Concat

e.g。

lst.Concat(callmethod()); // and optionally .ToList()

答案 1 :(得分:2)

这应该可以解决问题:

test.AddRange(CallAMethod());

答案 2 :(得分:0)

如何将列表作为CallAMethod的参数,并向其添加项目,而不是每次都返回一个新列表?

List<int> test = new List<int>();
CallAMethod(test); // add 1,2
CallAMethod(test); // add 6,8

然后将CallAMethod定义为

void CallAMethod(List<int> list) {
    list.Add( /* your values here */ );
}