C#迭代两个数组或List并将匹配放在第三个数组或列表中

时间:2016-09-29 17:33:42

标签: c# arrays matching

我有两个数组

List<int> a
List<int> b
List<int> matches

我需要将所有匹配放在第三个(匹配)数组中,以便我可以打印出来......

我可以像这样打印出a和b。

a.Sort();
label1.Text = "";
foreach (int x in a)
    label1.Text += x + " , ";
a.Clear();

等等&#34; b&#34;

但是如何比较两者并且只取匹配的整数,将它们放入&#34;匹配&#34;数组并以相同的方式打印出来?

1 个答案:

答案 0 :(得分:2)

您可以使用linq查询来获取两个列表中的值...

List<int> a = new List<int> {1,2,3};
List<int> b = new List<int> {2,4,6,3};

var matches = a.Intersect(b);

// Create comma-separated string of matching values...  
string output = string.Join(",", matches);