2017-07-21 100 views
0

我有以下方法需要MyExampleClass和id的數組。我正試圖解決的當前問題在該方法中進行了評論。如何比較兩個數組並用第一個數組更新第二個數組?

 public void Update(MyExampleClass[] example, int id) 
    { 
     //get the current values 
     var current = GetCurrentMyExampleClassValues(id); 

     //Compare the example and current arrays 

     //Update the OptedIn value for each item in the current array with the OptedIn value from the example array. 

     //The result is our new updated array 

     //Note that current array will always contain 3 items - Name1, Name2, Name3, 
     //but the example array can contain any combination of the 3. 
     var newArray = PsuedoCodeDoStuff(); 

     var result = _myService.Update(newArray); 
    } 


     private MyExampleClass[] GetCurrentMyExampleClassValues(int id) 
    { 
     var current = new MyExampleClass[] 
      { 
       new MyExampleClass {Name = "Name1", OptedIn = false }, 
       new MyExampleClass {Name = "Name2", OptedIn = true }, 
       new MyExampleClass {Name = "Name3", OptedIn = false } 
      }; 

     return current; 
    } 
+0

你想如何比較數組元素?按價值還是身份? – hoodaticus

+0

目前還不清楚您是否想用匹配的當前optedIn值更新傳入的數組(示例),反之亦然 – Steve

+0

當前數組的值始終爲Name1,Name2,Name3。我關心如何根據用戶在示例數組中傳遞的內容更新每個人的OptedIn值。 – generationalVision

回答

2

在我看來,你只需要遍歷當前數組。使用Name作爲鍵在示例數組中搜索當前數組中的每個項目。如果你發現它然後更新。

foreach(MyExampleClass item in current) 
{ 
    MyExampleClass exampleItem = example.FirstOrDefault(x => x.Name == item.Name); 
    if(exampleItem != null) 
     item.OptedIn = exampleItem.OptedIn; 
} 
+0

謝謝史蒂夫!這就是我需要的。 – generationalVision

相關問題