简体   繁体   中英

Add and remove objects from list with Linq

I'm trying to get a grip around Linq and have the following problem:

I have a list of a custom object, with a few properties for each object. I then have another list of the same type, where the property values will be different except for an ID property. Now, I want to add the objects that is found in my second list ( tempList ) that is not found in my first list ( OrderList ). After that I try to remove objects in OrderList that is not found in tempList .

This might seem a bit unnecessary, but the reason is that I need to keep the values of properties in OrderList if the ID of these are found in the tempList , hence not replace the object in OrderList with " empty " properties from tempList .

The code snippet looks like this ( OrderList and tempList has already been filled with objects, and it's the property ID I use as identifier):

// Add new orders from account to current object
OrderList.AddRange(tempList.Where(p => !OrderList.Any(p2 => p2.ID == p.ID)));

// Remove missing orders from our OrderList
OrderList.RemoveAll(p => !tempList.Any(p2 => p2.ID == p.ID));

There is something I'm doing wrong since the properties of an object in OrderList gets reset after each of the two lines...

Maybe a fresh set of eyes can see what I'm doing wrong?

Try this:

void Main()
{
    var orList = new List<A> {new A {Id = 0, S = "a"}, new A {Id = 1, S = "b"}, new A {Id = 2, S = "c"}, new A {Id = 4, S = "e"}};
    var tmList = new List<A> {new A {Id = 2, S = "cc"}, new A {Id = 3, S = "dd"}};

    var result = orList.Union(tmList, new AComparer()).ToList();
    result.RemoveAll(a => tmList.All(at => at.Id != a.Id));
}

public class A {
    public int Id;
    public string S;
}

class AComparer : IEqualityComparer<A> {
    public bool Equals(A x, A y) { return x.Id == y.Id; }
    public int GetHashCode(A a) { return a.Id; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM