Shivi
Shivi

Reputation: 1085

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();   // 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?

Upvotes: 1

Views: 179

Answers (3)

Paolo Tedesco
Paolo Tedesco

Reputation: 57222

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

Upvotes: 0

James Allen
James Allen

Reputation: 819

This should do the trick:

test.AddRange(CallAMethod());

Upvotes: 2

Pranay Rana
Pranay Rana

Reputation: 176936

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()

Upvotes: 3

Related Questions