如何改变不改变原始列表我的新名单? [英] How do I change my new list without changing the original list?

查看:144
本文介绍了如何改变不改变原始列表我的新名单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有获取与从操作的一些数据填充列表,我将其存储在内存缓存。现在我想其中包含基于一些条件列表中的某些子数据另一个列表。



由于可以在下面的代码可以看到我做的目标名单上的一些操作。现在的问题是,无论改变我做的目标列表也正在做给mainList。我认为它是因为引用是相同或东西。



所有我需要的是目标列表上的操作不影响主列表中的数据。

 列表<项目>目标= mainList; 
SomeOperationFunction(目标);

作废名单,LT;项目> SomeOperationFunction(列表<项目>目标)
{
target.removeat(3);
回报率的目标;
}


解决方案

您需要克隆列表在你的方法,因为列表< T> 是一个类,所以它的引用类型和通过引用传递



例如:

 列表<项目> SomeOperationFunction(列表<项目>目标)
{
名单,LT;项目> TMP = target.ToList();
tmp.RemoveAt(3);
返回TMP;
}

 列表<项目> SomeOperationFunction(列表<项目>目标)
{
名单,LT;项目> TMP =新的List<项目>(目标);
tmp.RemoveAt(3);
返回TMP;
}

 列表<项目> SomeOperationFunction(列表<项目>目标)
{
名单,LT;项目> TMP =新的List<项目>();
tmp.AddRange(目标);
tmp.RemoveAt(3);
返回TMP;
}


I have a list that gets filled in with some data from an operation and I am storing it in the memory cache. Now I want another list which contains some sub data from the list based on some condition.

As can be seen in the below code I am doing some operation on the target list. The problem is that whatever changes I am doing to the target list is also being done to the mainList. I think its because of the reference is same or something.

All I need is that operation on the target list not affect data inside the main list.

List<Item> target = mainList;
SomeOperationFunction(target);

 void List<Item> SomeOperationFunction(List<Item> target)
{
  target.removeat(3);
  return target;
}

解决方案

You need to clone your list in your method, because List<T> is a class, so it's reference-type and is passed by reference.

For example:

List<Item> SomeOperationFunction(List<Item> target)
{
  List<Item> tmp = target.ToList();
  tmp.RemoveAt(3);
  return tmp;
}

Or

List<Item> SomeOperationFunction(List<Item> target)
{
  List<Item> tmp = new List<Item>(target);
  tmp.RemoveAt(3);
  return tmp;
}

or

List<Item> SomeOperationFunction(List<Item> target)
{
  List<Item> tmp = new List<Item>();
  tmp.AddRange(target);
  tmp.RemoveAt(3);
  return tmp;
}

这篇关于如何改变不改变原始列表我的新名单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆