Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check difference between 2 IEnumerables

So basically I have the following 2 IEnumerable lists

List A = {"Personal", "Tech", "Social"}
List B = {"Personal", "Tech", "General"}

Now what I want to achieve is, get the difference between List A and List B, in this case Social and General.

I also need to determine that Social is extra in List A and General is extra in List B to insert and delete accordingly.

I can also have another scenario

 List A = {"Personal", "Tech"}
 List B = {"Personal", "Tech", "General"}

in this case it would return General"

How can I do that with LINQ?

like image 802
JMon Avatar asked Jan 10 '13 12:01

JMon


2 Answers

Here you go

var ListA = new List<string> {"Personal", "Tech", "Social"};
var ListB = new List<string> { "Personal", "Tech", "General" };

var insert = ListA.Except(ListB).ToList();
var delete = ListB.Except(ListA).ToList();
like image 50
alexb Avatar answered Nov 02 '22 17:11

alexb


You can use List<T>.Except() Method.

Produces the set difference of two sequences.

        public static void Main(string[] args)
        {
            List<string> A = new List<string> { "Personal", "Tech", "Social" };
            List<string> B = new List<string> { "Personal", "Tech", "General" };

            var result = A.Except(B);

            //Will print "Social"
            foreach (var i in result)
            {
                Console.WriteLine(i);
            }
        }

Here is a DEMO.

For your second case;

        public static void Main(string[] args)
        {
            List<string> A = new List<string> { "Personal", "Tech" };
            List<string> B = new List<string> { "Personal", "Tech", "General"};

            var result = B.Except(A);

            foreach ( var i in result )
            {
                Console.WriteLine(i);
            }
        }

Here is a DEMO.

like image 45
Soner Gönül Avatar answered Nov 02 '22 18:11

Soner Gönül