2017-07-21 15 views
0

私はMyExampleClassとidの配列をとる以下のメソッドを持っています。私が解決しようとしている現在の問題は、このメソッドにコメントされています。2つの配列を比較し、2番目の配列を最初の配列の値で更新するにはどうすればよいですか?

 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値またはviceversaで更新するかどうかはわかりません – 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

ありがとうSteve!それだけが必要。 – generationalVision

関連する問題