.NET\C#日常开发随手记----解决一个集合引用另一个集合导致一起改变

197 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

问题:

以一个集合为基础,将筛选后的集合赋值给另一个集合之后更改第二个集合的值会导致第一个集合的数据跟着变动

image.png

深度拷贝(已封装为一个泛型通用方法复制即用):

/// <summary>
/// 深度拷贝集合方法----解决一个集合引用另一个集合导致一起改变
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list1"></param>
/// <param name="list2"></param>
/// <returns></returns>
public static List<T> DeepCopyList<T>(IList<T> list1 , out List<T> list2)
{
	MemoryStream ms = new MemoryStream();
	BinaryFormatter bf = new BinaryFormatter();
	bf.Serialize(ms, list1);
	ms.Position = 0;
	list2 = (List<T>)bf.Deserialize(ms);
	return list2;
}

使用到的类(类需要标记可序列化特性):

[Serializable]
public class Student
{
	public int Id { get; set; }

	public int Age { get; set; }

}

测试方法:

static void Main(string[] args)
{
	var list1 = new List<Student>();
	Student stu1 = new Student();
	stu1.Id = 1;
	stu1.Age = 12;
	list1.Add(stu1);

	Student stu2 = new Student();
	stu2.Id = 2;
	stu2.Age = 21;
	list1.Add(stu2);

	Student stu3 = new Student();
	stu3.Id = 3;
	stu3.Age = 23;
	list1.Add(stu3);

	var list2 = new List<Student>();
	list2 = DeepCopyList<Student>(list1,out list2).Where(s => s.Id == 1).ToList();

	var ss = list2.Select(s => s.Age = 33).ToList();
}

结果: 在这里插入图片描述

转json

/// <summary>
/// 转json方法----解决一个集合引用另一个集合导致一起改变
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <returns></returns>
public static List<T> Clone<T>(this List<T> list) where T : new()
{
	var str = JsonConvert.SerializeObject(list);
	return JsonConvert.DeserializeObject<List<T>>(str);
}

使用到的类(类需要标记可序列化特性):

[Serializable]
public class Student
{
	public int Id { get; set; }

	public int Age { get; set; }

}

测试方法:

static void Main(string[] args)
{
	var list1 = new List<Student>();
	Student stu1 = new Student();
	stu1.Id = 1;
	stu1.Age = 12;
	list1.Add(stu1);

	Student stu2 = new Student();
	stu2.Id = 2;
	stu2.Age = 21;
	list1.Add(stu2);

	Student stu3 = new Student();
	stu3.Id = 3;
	stu3.Age = 23;
	list1.Add(stu3);

	var list2 = new List<Student>();
	list2 = Clone<Student>(list1).Where(s => s.Id == 1).ToList();

	var ss = list2.Select(s => s.Age = 33).ToList();
}

结果: 在这里插入图片描述