linq选择列表中项目的属性不在另一个列表中的项目属性中的项目

时间:2014-05-01 12:01:10

标签: linq join except

我有两个不同类型的两个列表。我想选择第一个列表中具有属性(我们称之为名称)的所有项目,这些项目在另一个列表中没有相同名称的对应对象。

例如,如果我有一个Age项目列表(joe,4),(marry,5),(ed,2)

和另一个关系项目列表(乔,父亲),(编辑,兄弟)

我想最终得到(结婚,5)

的结果列表

我不确定是否"除了"以某种方式在这里使用。

1 个答案:

答案 0 :(得分:0)

鉴于不同类型的两个数组(我在这里使用的是匿名类型,但它与正确类的处理相同),您将需要首先提取例外的“密钥”。在这种情况下,'key'是Name属性。

//Setup
var ageItems = new [] { new {Name = "Joe", Age=4}, new {Name = "Marry", Age=5}, new {Name="Ed", Age=2} };
var relationItems = new [] { new {Name="Joe", Rel = "Father"}, new {Name="Ed", Rel="Brother"} };

//Get the names
var exceptedNames = ageItems.Select (a => a.Name).Except(relationItems.Select (r => r.Name));

//At this point, we have an `IEnumerable` containing 'Marry', we need to get the instances
var exceptedItems = ageItems.Where(a => exceptedNames.Contains(a.Name));

当然,作为LINQ,你可以把它全部打成一个电话:

var exceptedItems = ageItems.Where (a => ageItems.Select (b => b.Name).Except(relationItems.Select (r => r.Name)).Contains(a.Name));

由于您的类不同,您无法使用.Except实例的IEqualityComparer重载,IEqualityComparer只能比较同一类型的两个项目,因此我们必须推广并拉出相同的领域。