两个数组的C#异同 [英] C# Similarities of two arrays

查看:133
本文介绍了两个数组的C#异同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

必须是一种更好的方式来做到这一点,我相信...

There must be an better way to do this, I'm sure...

// Simplified code
var a = new List<int>() { 1, 2, 3, 4, 5, 6 };
var b = new List<int>() { 2, 3, 5, 7, 11 };
var z = new List<int>();
for (int i = 0; i < a.Count; i++)
    if (b.Contains(a[i]))
        z.Add(a[i]);
// (z) contains all of the numbers that are in BOTH (a) and (b), i.e. { 2, 3, 5 }

我不介意使用上述技术,但我想要的东西快速,高效的(我需要比较非常大的列表&LT;>多次),这似乎是没有!有什么想法?

I don't mind using the above technique, but I want something fast and efficient (I need to compare very large Lists<> multiple times), and this appears to be neither! Any thoughts?

编辑:由于它的确与众不同 - 我使用.NET 4.0,最初的数组已经排序,并且不包含重复

As it makes a difference - I'm using .NET 4.0, the initial arrays are already sorted and don't contain duplicates.

推荐答案

您可以使用IEnumerable.Intersect。

You could use IEnumerable.Intersect.

var z = a.Intersect(b);

这将的可能的比当前解决方案更加有效。

which will probably be more efficient than your current solution.

请注意你离开出一个重要的信息 - 名单是否发生下令与否。如果他们是那么一对夫妇的传递在每个输入数组恰好每一次可能更快嵌套的循环 - 和一点点更有趣的写

note you left out one important piece of information - whether the lists happen to be ordered or not. If they are then a couple of nested loops that pass over each input array exactly once each may be faster - and a little more fun to write.

修改
在回答您的评论排序:

Edit In response to your comment on ordering:

在循环首次尝试 - 它的将会的需要一点点调整以您的名义,但适用于您的初始数据

first stab at looping - it will need a little tweaking on your behalf but works for your initial data.

    int j = 0;
    foreach (var i in a)
    {
        int x = b[j];
        while (x < i)
        {
            if (x == i)
            {
                z.Add(b[j]);
            }
            j++;
            x = b[j];
        }
    }

这就是你需要添加一些单元测试;)

this is where you need to add some unit tests ;)

修改
最后一点 - 它可能是,LINQ的可以使用排序列表非常高效地执行此交汇,如果性​​能是一个问题很值得测试各种解决方案。不要忘记采取分类考虑,如果你加载一个未排序的方式您的数据。

Edit final point - it may well be that Linq can use SortedList to perform this intersection very efficiently, if performance is a concern it is worth testing the various solutions. Dont forget to take the sorting into account if you load your data in an un-ordered manner.

研究最后修改是因为有一些来来回回就这个问题和人可能使用上述没有正确调试它,我在这里张贴更高版本:

One Final Edit because there has been some to and fro on this and people may be using the above without properly debugging it I am posting a later version here:

        int j = 0;
        int b1 = b[j];
        foreach (var a1 in a)
        {
            while (b1 <= a1)
            {
                if (b1 == a1)
                    z1.Add(b[j]);
                j++;
                if (j >= b.Count)
                    break;
                b1 = b[j];
            }
        }

这篇关于两个数组的C#异同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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