如何在C#中使用linq/lambda获取数据副本而不是引用?
问题描述:
是否有一种简单的方法来基本上只获取数据的副本而不是使用此方法的引用?我尝试了.ToArray().Where(),但这似乎仍然可以通过引用.
Is there an easy way to basically just get a copy of the data instead of a reference using this method? I tried .ToArray().Where() but that still seems to pass a reference.
示例:
static void Main(string[] args)
{
List<ob> t = new List<ob>();
t.Add(new ob() { name = "hello" });
t.Add(new ob() { name = "test" });
ob item = t.Where(c => c.name == "hello").First();
// Changing the name of the item changes the original item in the list<>
item.name = "burp";
foreach (ob i in t)
{
Console.WriteLine(i.name);
}
Console.ReadLine();
}
public class ob
{
public string name;
}
答
您需要自己创建ob
的副本-这不是LINQ提供的.
You need to create a copy of your ob
yourself - it's not something LINQ provides.