2017-07-21 99 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

相关问题