先遍历一个数组,依次取出一个,然后遍历另外的一个数组,找到相同的记录下来。不过最好是排个顺序,这样算法能优化下,另外一个数组就不用每次都全部Look了。

解决方案 »

  1.   

    int[] array1 = new int[] { 1, 2, 3, 4, 5, 6, 7, 8 };
                int[] array2 = new int[] { 5, 6, 7, 8, 9 };
                string str = string.Empty;            for (int i = 0; i < array1.Length; i++) 
                {
                    for (int j = 0; j < array2.Length; j++) 
                    {
                        if (array1[i].Equals(array2[j])) 
                        {
                            str = str + array1[i].ToString();
                            
                        }
                    }
                }
      

  2.   

    using System;
    using System.Collections.Generic;class Test
    {
      static void Main()
      {
        int[] a = { 1, 2, 3, 4, 5, 6, 7, 8 };
        int[] b = { 5, 6, 7, 8, 9 };
        int[] c = FindSame(a, b);  // 这就是你要的。
        foreach (int x in c)
        {
          Console.WriteLine(x);
        }
        Console.ReadLine();
      }  static int[] FindSame(int[] a, int[] b)
      {
        List<int> c = new List<int>();
        foreach (int x in a)
        {
          foreach (int y in b)
          {
            if (x == y) c.Add(x);
          }
        }
        return c.ToArray();
      }
    }
      

  3.   

    用Linq的话,超简单:
                var a = new int[] { 1, 2, 3, 4, 5, 6, 7, 8 };
                var b = new int[] { 5, 6, 7, 8, 9 };
                foreach (var item in a.Intersect(b))
                {
                    Console.WriteLine(item);
                }
                Console.ReadLine();
      

  4.   

    楼上的楼上的楼上没忽悠...正解...改成这样便于理解...int[] a = new int[] { 1, 2, 3, 4, 5, 6, 7, 8 };
    int[] b = new int[] { 5, 6, 7, 8, 9 };
    List<int> c = new List<int>();
    c.AddRange(a.Intersect(b));
    int[] d = c.ToArray();
      

  5.   

    不过说到Linq上去是有点算忽悠了...这个Intersect只能算.NET 3.5的新特性...
      

  6.   

    可以定义多维的数组? 然后再循环? 可以取出来?  我记得貌似我在 用matlab的时候碰到过如此问题.
      

  7.   

    我对18楼的言论表示道歉,我不知道3.5那个Intersect,只是从2.0的MSDN里查到关于权限交集的Intersect。误会了,不好意思。
      

  8.   

    好吧,那就写个标准点的Linq,这次不算忽悠了吧
                int[] a = new int[] { 1, 2, 3, 4, 5, 6, 7, 8 };
                int[] b = new int[] { 5, 6, 7, 8, 9 };
                var c = from x in a
                        join y in b on x equals y
                        select x;
                foreach (int item in c)
                {
                    Console.WriteLine(item);
                }
      

  9.   


    int[] a = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    int[] b = new int[] { 1, 34, 2, 3, 4, 65, 76, 5, 9 };
    for (int i = 0; i < a.Length; i++)
    {
        Console.WriteLine(Array.IndexOf(b, a[i]) != -1?a[i].ToString():"");
    }