手记

获取2个集合List<T>的共同元素

获取2个集合List<T>的共同元素,循环2个集合,然后比对。

 

class Bj    {        public void GetIntersect()        {            var listA = new List<int> { 2, 5, 6, 8, 23, 56, 4 };            var listB = new List<int> { 1, 6, 9, 11, 34, 29, 5, 23, 4 };            foreach (int a in listA)            {                foreach (int b in listB)                {                    if (a == b)                    {                        Console.WriteLine(a);                    }                }            }        }    }

Source Code

 

普通方法,运行结果:

 

其实,你可以使用Intersect()交集的方法,可令代码更为简单:

 

 var listC = listA.Intersect(listB);            foreach (int c in listC)            {                Console.WriteLine(c);            }

Source Code

 

看看结果:

 

0人推荐
随时随地看视频
慕课网APP