Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Comparing Two Lists - Add new, remove old, leave the ones in common

Tags:

c#

list

linq

I have two lists (L1,L2) of an object A, L1 is used to store the list of objects(many to many relationship) before they are changed. L2 is the relationship after it has been changed. I need to keep the common elements but add the new ones and remove the ones that aren't in L2. I was wondering if there was a one liner I could use with LINQ to accomplish this. If you need more information just let me know.

Thanks in advance

like image 889
Gage Avatar asked Sep 14 '10 17:09

Gage


2 Answers

If I understood your requirements correctly, this should work:

L1.AddRange(L2.Except(L1));
L1.RemoveAll(item => !L2.Contains(item));

Not a one-liner, but close enough...

like image 132
Thomas Levesque Avatar answered Sep 21 '22 15:09

Thomas Levesque


try something like this

var a = from ele in list1
        let alleles = list1.Union(list2)
        let deleles = alleles.Except(list1)
        let neweles = alleles.Except(list2)
        select new { DeletedEles = deleles, NewEles = neweles };
like image 28
Vinay B R Avatar answered Sep 22 '22 15:09

Vinay B R