开发者

Append values to a list

Is there any way to add a list of numbers to a List<int> without using a loop?

My scenario:

List<int> test = CallAMethod();开发者_如何学Go   // It will return a List with values 1,2

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

But now the second set of values will replace the first set. Is there any way to append the values to the list without a for-loop?


List.AddRange Method

You'd need to do something like:

lst.AddRange(callmethod());

Alternatively, C# 3.0, simply use Concat,

e.g.

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


This should do the trick:

test.AddRange(CallAMethod());


What about having the list as a parameter to CallAMethod, and adding items to it, instead of returning a new list each time?

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

Then you define CallAMethod as

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜