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();
} } }
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(); } }
用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();
楼上的楼上的楼上没忽悠...正解...改成这样便于理解...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();
好吧,那就写个标准点的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); }
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():""); }
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();
}
}
}
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();
}
}
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();
int[] b = new int[] { 5, 6, 7, 8, 9 };
List<int> c = new List<int>();
c.AddRange(a.Intersect(b));
int[] d = c.ToArray();
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);
}
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():"");
}