【问题标题】:how compare two int[] array for update and merge the difference?如何比较两个 int[] 数组以进行更新和合并差异?
【发布时间】:2013-12-22 08:43:42
【问题描述】:

我想知道是否有一种简单的方法来比较两个整数数组并在第一个数组源中按顺序添加缺失的元素。

示例代码:

        //Two list [source , compare ]
        public int[] ListSource = new int[]{ 4,8,12,20,24,32 } ;
        public int[] ListToCompare = new int[] { 3, 8, 16, 16, 20, 24, 28, 32,36 };

        //If size of array is different , we resize the source
        if(ListSource.Length != ListToCompare.Length)
        {
            Array.Resize(ref ListSource, ListToCompare.Length);
        }

        // Compare and update
        for(int a = 0 ; a < ListToCompare.Length;a++)
        {
            if(ListSource[a] != ListToCompare[a])
            {
                // .... How can i do it 
            }
        }

        //And finally my Listsource is complete merge with the listToCompare and in good order
        //ListSource = { 3, 4, 8, 12, 16, 16, 20, 24, 28, 32 };

非常感谢:-)

【问题讨论】:

  • 输入是否保证已经排序?
  • 如果这些来源总是排序的(所以顺序是已知的),你可以UnionOrderBy。如果不是 - 它将不适用。
  • 不应该在您的示例答案末尾有36 吗?
  • 你的结果中的 16 是不是打错字了?
  • 是的,很抱歉打错了“16”

标签: c# .net arrays merge compare


【解决方案1】:
//Here   is a sample on  how you can achieve this  

 static void Main(string[] args)
    {
       //Two list [source , compare ]
    int[] ListSource = new int[]{ 4,8,12,20,24,32 } ;
    int[] ListToCompare = new int[] { 3, 8, 16, 16, 20, 24, 28, 32,36 };


        var res = ListToCompare.Except(ListSource);
        var NewListSource = ListSource.ToList();
        NewListSource.AddRange(res);
       ListSource = NewListSource.OrderBy(x=>x).ToArray();  




        //And finally my Listsou
    }
}

【讨论】:

  • 恐怕连编译都不会
  • 结果不会是双 16
  • 是的,但我认为这是用户给出的示例中的错误输入
  • 不这么认为,但也许OP会给我们一个答案
  • 所以您认为缺少 36 而不是 16 是错误的输入:)
【解决方案2】:

试试这个:

ListSource = ListToCompare.Where(x=>!ListSource.Contains(x))
                                .Concat(ListSource).OrderBy(x => x).ToArray();

在此处查看结果:http://ideone.com/6CY4lp

它将保留示例结果中的双 16

【讨论】:

  • Distinct() 不好 - 如果一个数字在其中一个列表中出现两次,OP 希望保留一个数字的两个实例;请参阅他的示例答案中重复的16
  • @MatthewWatson 好的,谢谢,我会更改它,现在它应该返回好的列表
  • 现在看来是正确的。我认为 OP 从他的示例答案末尾错过了36
  • @MatthewWatson 是的,我认为这是一个错字。
  • 谢谢它也很好用。但我只能选择一个答案。所以再次感谢。我回答你^^
【解决方案3】:
var set = new HashSet<int>();
set.UnionWith(ListSource);
set.UnionWith(ListToCompare);
ListSource = set.OrderBy(x => x).ToArray();

【讨论】:

    【解决方案4】:

    你可以试试这个:

    var except = list2.Except(list1);
    var result = list1.Union(except).OrderBy(x => x);
    

    或短

    var result = list1.Union(list2.Except(list1)).OrderBy(x => x);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-02
      • 2013-11-26
      • 2013-04-27
      相关资源
      最近更新 更多