2013-04-05 65 views
4
public class MyObject1 
{ 
    public Guid g1; 
    public Guid g2; 
    public Guid g3; 
} 

public class MyObject2 
{ 
    public Guid g4; 
} 


List<MyObject1> list1; 
List<MyObject2> list2; 

我想一个LINQ查询将返回列表1中的所有对象MyObject1其中MyObject1.g2 == MyObject2.g4其中MyObject2对象居住在列表2LINQ到比较对象的两个列表,其中一个对象有几个列表

我已经写了很多步骤做到这一点的代码,但我想我可以在一次迭代中做到这一点。

所以像

var n = list1.Select(p=> p.g2).ToList() 

var o = list2.Intersect(n) 

,但现在我需要研究列表1使用邻又是尴尬

回答

12

这听起来像你想有一个join

var query = from x1 in list1 
      join x2 in list2 on x1.g2 equals x2.g4 
      select x1; 

还是在扩展方法语法:

var query = list1.Join(list2, x1 => x1.g2, x2 => x2.g4, (x1, x2) => x1); 

请注意,这样只会让你的项目从list1 - 如果你从list2需要相应的项目为好,这是简单的:

var query = from x1 in list1 
      join x2 in list2 on x1.g2 equals x2.g4 
      select new { x1, x2 }; 
+1

+1乔恩,我希望你不要让那个狡猾的扩展方法连接语法作为替代,虽然;) – mattytommo 2013-04-05 21:26:59

+0

@mattytommo - 但是...我喜欢的扩展方法 – 2013-04-06 02:52:22

+0

@ScottSelby即使连接和组BYS? Eeeeek:P – mattytommo 2013-04-06 10:46:36

1

如何:

var results = 
    from a in list1 
    join b in list2 on a.g2 equals b.g4 
    select a; 

这将返回所有来自list1的项目,其中list2中存在与MyObject1.g2 == MyObject2.g4中的项目。

3
var query = list1.Where(l1 => list2.Any(l2=> l2.g4 == l1.g2)); 
相关问题