在特定属性上使用 LINQ to object Intersect 和 except
当我有 2 个 List
对象时,我可以直接对它们使用 Intersect
和 Except
来获取输出 IEnumerable<字符串>
。这很简单,但是如果我想要更复杂的东西的交集/析取怎么办?
例如,尝试获取 ClassA
对象的集合,该集合是 ClassA
对象的 AStr1
和 ClassB
相交的结果> 对象的 BStr
; :
public class ClassA {
public string AStr1 { get; set; }
public string AStr2 { get; set; }
public int AInt { get; set; }
}
public class ClassB {
public string BStr { get; set; }
public int BInt { get; set; }
}
public class Whatever {
public void xyz(List<ClassA> aObj, List<ClassB> bObj) {
// *** this line is horribly incorrect ***
IEnumberable<ClassA> result =
aObj.Intersect(bObj).Where(a, b => a.AStr1 == b.BStr);
}
}
我怎样才能修复标注的线以实现这个交叉点。
When I have 2 List<string>
objects, then I can use Intersect
and Except
on them directly to get an output IEnumerable<string>
. That's simple enough, but what if I want the intersection/disjuction on something more complex?
Example, trying to get a collection of ClassA
objects which is the result of the intersect on ClassA
object's AStr1
and ClassB
object's BStr
; :
public class ClassA {
public string AStr1 { get; set; }
public string AStr2 { get; set; }
public int AInt { get; set; }
}
public class ClassB {
public string BStr { get; set; }
public int BInt { get; set; }
}
public class Whatever {
public void xyz(List<ClassA> aObj, List<ClassB> bObj) {
// *** this line is horribly incorrect ***
IEnumberable<ClassA> result =
aObj.Intersect(bObj).Where(a, b => a.AStr1 == b.BStr);
}
}
How can I fix the noted line to achieve this intersection.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
MoreLINQ 具有
ExceptBy
。它还没有IntersectBy
,但您可以轻松编写自己的实现,甚至可能随后将其贡献给 MoreLINQ :)它可能看起来像这样(省略错误检查):
如果您想对两个完全不同的类型执行交集,而这两个类型恰好具有共同的属性类型,您可以创建一个具有三个类型参数的更通用的方法(一个用于
first
,一个用于第二个
,第一个用于公共密钥类型)。MoreLINQ has
ExceptBy
. It doesn't haveIntersectBy
yet, but you could easily write your own implementation, and possibly even contribute it to MoreLINQ afterwards :)It would probably look something like this (omitting error checking):
If you wanted to perform an intersection on two completely different types which happened to have a common property type, you could make a more general method with three type parameters (one for
first
, one forsecond
, and one for the common key type).x ε A ∩ B 当且仅当 x ε A 且 x ε B 时。
因此,对于
aObj
中的每个a
,您可以检查是否a.AStr1< /code> 位于
BStr
值集中。x ∈ A ∩ B if and only if x ∈ A and x ∈ B.
So, for each
a
inaObj
, you can check ifa.AStr1
is in the set ofBStr
values.该代码:
已通过以下测试:
this code:
has passed the following test: