![](/img/trans.png)
[英]LINQ to remove objects from a list of objects based on another list of objects
[英]Add and remove objects from list with Linq
我正在设法控制Linq并遇到以下问题:
我有一个自定义对象的列表,每个对象都有一些属性。 然后,我有另一个相同类型的列表,其中除了ID属性之外,属性值将有所不同。 现在,我想补充一点,在我的第二个表(找到的对象tempList
未在我的第一个列表(发现) OrderList
)。 之后,我尝试删除OrderList
中没有在tempList
找到的tempList
。
这似乎有点多余,但原因是,我需要保持在属性值OrderList
如果这些标识在发现tempList
,因此不能更换对象OrderList
与“ 空 ”的属性tempList
。
代码段如下所示( OrderList
和tempList
已经填充了对象,这是我用作标识符的属性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));
我做错了什么,因为在两行中的每一行之后,OrderList中对象的属性都被重置了...
也许新鲜的眼睛可以看到我在做什么错?
尝试这个:
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.