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
?
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();
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With