如何比较两个数组并使用第一个数组的值更新第二个数组?

时间:2017-07-21 21:37:00

标签: c# arrays ienumerable

我有以下方法接受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;
    }

1 个答案:

答案 0 :(得分:2)

在我看来,你只需要遍历当前数组。使用Name作为键在示例数组中搜索当前数组中的每个项目。如果你找到它然后更新。

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