tags:

views:

114

answers:

4

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

+6  A: 

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...

Thomas Levesque
+1  A: 

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 };
Vinay B R
+1  A: 

Perhaps I'm misunderstanding, but isn't what you are asking for the set of objects that are stored in L2?

To use a concrete example, if you have these inputs:

L1: { 1, 2, 3, 4, 5 }
L2: { 2, 3, 5, 7 }

Isn't the desired result { 2, 3, 5, 7 }?

Rob H
Yes but its for a many to many relationships and I want to be able to keep the currently relationships instead of wiping and creating new ones. I'm using Nhibernate and Castle ActiveRecord
Gage
+1  A: 

Maybe Linq's boolean operators like Intersect() could be of help to you?

Pompair