比较两个数组不同长度和显示差异中 [英] Compare Two Arrays Of Different Lengths and Show Differences

查看:221
本文介绍了比较两个数组不同长度和显示差异中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:


我有两个数组,可以可能是不同的长度。我需要通过两个数组进行迭代,找到相似之处,添加和删除。

什么是用C#实现这个最快和最有效的方式?

编辑:
数组是pre-排序,他们可以50-100项之间的任何牵制。另外,还有一些没有速度和/或内存使用任何约束(但是,没有人会喜欢一个内存猪;)


例如:

 的String [] = Foo_Old {测试1,测试2,TEST3};
的String [] = Foo_New {测试1,测试2,TEST4,TEST5};

 的String [] = Bar_Old {测试1,测试2,TEST4};
的String [] = Bar_New {测试1,TEST3};


的区别:

(相对于Foo_New阵列)


[同]测试1
[同]TEST2
[删除]TEST3
[新增]TEST4
[新增]TEST5

(相对于Bar_New阵列)


[同]测试1
[删除]TEST2
[删除]TEST4
[新增]TEST3


解决方案

您可以使用除了相交 ...

  VAR Foo_Old =新[] {测试1,测试2,TEST3};
VAR Foo_New =新[] {测试1,测试2,TEST4,TEST5};VAR差异= Foo_New.Except(Foo_Old);
VAR间= Foo_New.Intersect(Foo_Old);
VAR REM = Foo_Old.Except(Foo_New);的foreach(在差异变种S)
{
    Console.WriteLine(中增加了+ S);
}的foreach(国米VAR S)
{
    Console.WriteLine(相同+ S);
}的foreach(对物变种S)
{
    Console.WriteLine(已删除+ S);
}

Problem:
I have two arrays that can possibly be different lengths. I need to iterate through both arrays and find similarities, additions, and deletions.

What's the fastest and most efficient way to accomplish this in C#?

Edit: The arrays are pre-sorted and they can contain anywhere between 50-100 items. Also, there aren't any constraints on speed and/or memory usage (however, no one likes a memory hog;)


For example:

String[] Foo_Old = {"test1", "test2", "test3"};
String[] Foo_New = {"test1", "test2", "test4", "test5"};

AND

String[] Bar_Old = {"test1", "test2", "test4"};
String[] Bar_New = {"test1", "test3"};


Differences:

(with respect to the Foo_New array)

[Same]    "test1"
[Same]    "test2"
[Removed] "test3"
[Added]   "test4"
[Added]   "test5"

(with respect to the Bar_New array)

[Same]    "test1"
[Removed] "test2"
[Removed] "test4"
[Added]   "test3"

解决方案

You can use Except and Intersect ...

var Foo_Old = new[] { "test1", "test2", "test3" }; 
var Foo_New = new[] { "test1", "test2", "test4", "test5" };

var diff = Foo_New.Except( Foo_Old );
var inter = Foo_New.Intersect( Foo_Old );
var rem = Foo_Old.Except(Foo_New);

foreach (var s in diff)
{
    Console.WriteLine("Added " + s);
}

foreach (var s in inter)
{
    Console.WriteLine("Same " + s);
}

foreach (var s in rem)
{
    Console.WriteLine("Removed " + s);
}

这篇关于比较两个数组不同长度和显示差异中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆