Linq compare 2 lists – .Net Check if Items exist on Both Lists – .Net如何在2個Lists 中找出相同的Item 項目

今天需要寫一個功能去看看2個 List of String 上有那些String 是2個Lists內都有的

做了一會research後 終於找到解決方法了

我們可以使用 ListIntersect 功能

Linq - to get matched item from 2 lists of string

E.G.

            	// Source List with String A,B,C,D,E
            			List listA = new List();
            listA.Add("A");
            listA.Add("B");
            listA.Add("C");
            listA.Add("D");
            listA.Add("E");

            			// List To Compare with String 1,A,4,E,5
            List listB = new List();
            listB.Add("1");
            listB.Add("A");
            listB.Add("4");
            listB.Add("E");
            listB.Add("5");

          			// Retrieve the List of String which appear on both List
            List matchList = listA.Intersect(listB).ToList();

            for (int i = 0; i < matchList.Count; i++)
            {
               			// Output the list of matched string
                Console.WriteLine(matchList[i]);
            }

Happy Coding

2 thoughts on “Linq compare 2 lists – .Net Check if Items exist on Both Lists – .Net如何在2個Lists 中找出相同的Item 項目

  1. ShareChiWai Post author

    OMG… Sakamoto San, this is awesome, do not realise we can chain the code together like this.

    Thanks very much, I learnt a lot 🙂

    Happy coding

    Reply

Leave a Reply