问题描述
|
有没有办法在不使用循环的情况下将数字列表添加到“ 0”?
我的情况:
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循环的情况下将值追加到列表?
解决方法
List.AddRange方法
您需要执行以下操作:
lst.AddRange(callmethod());
或者,只需使用C#3.0
康卡特
例如
lst.Concat(callmethod()); // and optionally .ToList()
,这应该可以解决问题:
test.AddRange(CallAMethod());
,将列表作为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 */ );
}