我試圖從findall或where創建一個新列表,並修改該新列表而不更改原始列表。從FindAll創建list2並對list2進行更改時,它不應該影響list1。怎麼來的?asp.net從FindAll或Where修改列表而不修改搜索到的原始列表
編輯...兩個似乎工作的答案組合使用。任何預見的問題?編輯的工作代碼 編輯...它不工作。一個屬於對象屬性的類沒有複製其數據...任何想法?我看不出爲什麼複製或克隆對列表來說不簡單和簡單。
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Started");
List<SampleData> list1 = SampleData.MakeList(3);
for (int i = 0; i < list1.Count; i++)
{
Console.WriteLine("list1.Number => " + list1[i].Number);
Console.WriteLine("list1.Person => " + list1[i].Person);
}
List<SampleData> list2 = new List<SampleData>(list1.FindAll(m => m.Number == 1).Select(x => new SampleData().ShallowCopy())).ToList();
for (int i = 0; i < list2.Count; i++)
{
list2[i].Person = "Person " + list2[i].Number;
Console.WriteLine("list2.Number => " + list2[i].Number);
Console.WriteLine("list2.Person => " + list2[i].Person);
}
SampleData sd = list2.Find(s => s.Number == 1);
Console.WriteLine("Apartment Number" + sd.apartment.BuildingLetter); // <<<<------------------- THROWING NULL EXCEPTION FOR APARTMENT
Console.WriteLine("-------AFTER MODIFYING NEW LIST----LIST1.Person SHOULD BE NULL---");
for (int i = 0; i < list1.Count; i++)
{
Console.WriteLine("--list1.Number => " + list1[i].Number);
Console.WriteLine("--list1.Person => " + list1[i].Person);
}
for (int i = 0; i < list2.Count; i++)
{
Console.WriteLine("--list2.Number => " + list2[i].Number);
Console.WriteLine("--list2.Person => " + list2[i].Person);
}
Console.ReadLine();
System.Environment.Exit(0);
}
}
class SampleData
{
public int Number { get; set; }
public String Person { get; set; }
public Apartment apartment { get; set; }
public static List<SampleData> MakeList(int count)
{
List<SampleData> l = new List<SampleData>();
for (int i = 0; i < count; i++)
{
SampleData d = new SampleData();
d.apartment = new Apartment { RoomNumber = i, BuildingLetter = "letter-" + i };
d.Number = i;
l.Add(d);
}
return l;
}
public SampleData ShallowCopy()
{
return (SampleData)this.MemberwiseClone();
}
}
class Apartment
{
public int RoomNumber { get; set; }
public String BuildingLetter { get; set; }
}
顯然,當有另外的類屬性的一個不工作。屬於獨立類的屬性沒有複製其數據。查看編輯的代碼。 – user2828970