简体   繁体   English

使用Linq在列表中添加和删除对象

[英]Add and remove objects from list with Linq

I'm trying to get a grip around Linq and have the following problem: 我正在设法控制Linq并遇到以下问题:

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. 然后,我有另一个相同类型的列表,其中除了ID属性之外,属性值将有所不同。 Now, I want to add the objects that is found in my second list ( tempList ) that is not found in my first list ( OrderList ). 现在,我想补充一点,在我的第二个表(找到的对象tempList未在我的第一个列表(发现) OrderList )。 After that I try to remove objects in OrderList that is not found in tempList . 之后,我尝试删除OrderList中没有在tempList找到的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 . 这似乎有点多余,但原因是,我需要保持在属性值OrderList如果这些标识在发现tempList ,因此不能更换对象OrderList与“ ”的属性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): 代码段如下所示( OrderListtempList已经填充了对象,这是我用作标识符的属性ID ):

// 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... 我做错了什么,因为在两行中的每一行之后,OrderList中对象的属性都被重置了...

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; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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