2017-04-06 29 views
0

我試圖寫一個函數,其中將有兩個列表:更新數據更改我的所有數據

  1. 原始列表(fooList)
  2. 列表包含額外的信息(fooWithExtList)

但不知道爲什麼當我連接另一個列表中的文本時,它也更新我的原始列表中的信息。

下面的代碼:

var fooDataList = new List<Foo>(); 
    fooDataList.Add(new Foo { Bar = "Test1" }); 
    fooDataList.Add(new Foo { Bar = "Test2" }); 
    fooDataList.Add(new Foo { Bar = "Test3" }); 
    fooDataList.Add(new Foo { Bar = "Test4" }); 

    var fooList = new List<Foo>(); 
    var fooWithExtList = new List<Foo>(); 

    //assign foodata to fooList 
    fooDataList.ForEach(fdl => fooList.Add(fdl)); 

    //assign foodata to fooWithExtList 
    fooDataList.ForEach(fdl => fooWithExtList.Add(fdl)); 

    //set the fooWithExtList with extra info 
    fooWithExtList.ForEach(fwel => fwel.Bar = fwel.Bar + "ext"); 

    //merge the list 
    fooList = fooList.Concat(fooWithExtList).ToList(); 

結果:

Test1ext Test2ext Test3ext Test4ext Test1ext Test2ext Test3ext Test4ext

期待:

的Test1的Test2 TEST3 TEST4 Test1ext Test2ext Test3ext Test4ext

點網小提琴這裏:https://dotnetfiddle.net/0nMTmX

+0

您正在使用相同的_reference_,因此您會得到三個列表,指向第相同的數據。需要了解引用和值類型之間的區別。 – Steve

+0

類似於[C#Concepts:Value vs Reference Types](http://www.albahari.com/valuevsreftypes.aspx) – Steve

回答

1

你需要創建一個你,如果你希望他們存在作爲獨立的實體添加到第一列表中的Foo類的不同實例。否則,您將引用添加到您的三個列表中的同一個實例,因此,對其中一個Foo實例所做的更改將反映在三個列表中。

可能的解決方案。假設你的Foo類有一個複製方法....

public class Foo 
{ 
    public string Bar {get;set;} 
    public Foo(string bar) 
    { 
     Bar = bar; 
    } 
    public Foo Copy() 
    { 
     Foo aCopy = new Foo(this.Bar); 
     return aCopy; 
    } 
} 

現在你可以寫

//assign copies of foodata to fooList 
fooDataList.ForEach(fdl => fooList.Add(fdl.Copy())); 

如上評論指出,良好的讀數
C# Concepts: Value vs Reference Types
MSDN documentation
Or on this same site from Jon Skeet