开发者

Captured variable in C# function with a List<> parameter

开发者 https://www.devze.com 2023-01-05 07:42 出处:网络
I have the following sample codes.I don\'t 开发者_JS百科like to have lTest being captured and get the same value as lRet.I tried to introduce \"List<Test> lTest1 = lTest0;\" in the function AddM

I have the following sample codes. I don't 开发者_JS百科like to have lTest being captured and get the same value as lRet. I tried to introduce "List<Test> lTest1 = lTest0;" in the function AddMore2Test. It does not work. What is the proper way to do this?

Thanks!

Codes -

private void Test(){
  List<Test> lTest = GetInitTestList();

  List<Test> lRet = AddMore2Test(lTest);
}

private List<Test> AddMore2Test (List<Test> lTest0) {
  List<Test> lTest1 = lTest0;

  return lTest1.Where(…);
}


So at the end of it all you want lTest to contain an initial set of values, and lRet to contain those initial values, but with a bit of filtering applied? The problem is you are dealing with references, so ultimately everything is pointing at the same list. A quick, simple fix is to just do this:

List<Test> lRet = AddMore2Test(lTest.ToList());


I think you will probably want to use the List class' AddRange(IEnumerable list) method on the lRet instead of assinging the value:

lRet.AddRange(AddMore2Test(lTest))

EDIT: in the comments it was pointed out that lRet hadn't yet been initialized, so here is a viable change:

var lRet = new List<Test>(AddMore2Test(lTest));
0

精彩评论

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