我有两个相同类类型的列表。该类的属性是:
public string Name { get; set; }
public string Severity { get; set; }
public DateTime DetectedMissingUTC { get; set; }
public DateTime DetectedMissingLocal { get; set; }
考虑列表A包含以下内容的情况:
[0] Item.Name = "Bob"
[1] Item.Name = "Rob"
列表B包含:
[0] Item.Name = "Bob"
[1] Item.Name = "Rob"
[2] Item.Name = "Robert"
我想对[2] Item.Name = "Robert"
做点什么,因为它是一个新条目。我怎么能为此编码?我需要用乱码伪代码表示:
foreach (var ListB.item NOT IN ListA)
{
Do something with item
}
答案 0 :(得分:4)
这可以给你你想要的东西:
foreach (var item in ListB.Where(x => !ListA.Any(a => a.Name == x.Name))
{
...
}
如果您要将所有项目添加到仅listA
中存在的ListB
,您可以执行以下操作:
ListA.AddRange(ListB.Where(x => !ListA.Any(a => a.Name == x.Name));
答案 1 :(得分:0)
这就是我要做的。如果您不知道如何定义CustomEqualityComparer只是Google IEqualityComparer
。
foreach (var item in ListB.Except(ListA, new CustomEqualityComparer())
{
item.DoSomething();
}
答案 2 :(得分:0)
您可以这样做:
var newItem = ListB.Select(c => c.Name).Except(ListA.Select(c = c.Name));
//make use of your new item.
Console.Write(newItem.Name);