2010-09-26 90 views
0

旧的linq只是有点生锈。 如果我有2个集合EG NewCustomerList和OldCustomerList,看看是否已经存在一个姓氏,我将如何在linq中执行它。我确信有很多方法。 SelectMany响了一声,但忘了该怎么做!如何检查项目是否存在于2个observableCollection中linq

在forEach我会做这样的事情。 linq中的等价物是什么?

 foreach (var oldCustomer in OldCustomerList) 
    { 
     foreach (var newCustomer in NewCustomerList.Where(x => x.Surname == oldCustomer.Surname)) 
     { 
      break; 
     } 
    } 

有什么建议吗?非常感谢

回答

4

因此,您试图查看旧客户姓氏的任何是否在新客户列表中?

一个简单的选择:做一个连接,看看它是否是空的:(我用一个空的投影,因为我们真的不关心连接结果)

if (OldCustomerList.Join(NewCustomerList, x => x.Surname, x => x.Surname, 
         (x, y) => null).Any()) 
{ 
    ... 
} 

另一个选项:

var oldSurnames = new HashSet<string>(OldCustomrList.Select(x => x.Surname)); 
if (NewSurnameList.Any(x => oldSurnames.Contains(x.Surname)) 
{ 
    ... 
} 

我怀疑你可能会发现你真的想无论在哪个姓氏是常见的,但...如果你可以给我们更多的情况下,我们也许能够帮助你更加的结果。

+0

谢谢你的回复。你的例子真的帮助我明白了。上面只是一个不合理的例子,我把它们放在一起来理解你如何处理2个藏品,当你想要找到一个具有特定属性EG Surname的物品是否存在另一个集合。我是否与SelectMany脱离关系?感谢您的帮助 – user451259 2010-09-26 07:35:48

+0

@ user451259:SelectMany应该是您的嵌套的foreach代码的一个非常直接的翻译 - 但效率很低。如果你明白我的意思,这是O(n * m)的方法,而不是我的代码的O(n + m)方法。 – 2010-09-26 07:49:45

2

你可以这样做:

NewCustomerList.Where(n => OldCustomerList.Any(o => o.Surname == n.Surname)) 
1

这里的另一种方法,其中也有O(n + m)复杂性+快捷通语义:

OldCustomerList.Select(cust => cust.Surname) 
       .Intersect(NewCustomerList.Select(cust => cust.Surname)) 
       .Any(); 

IMO,它比一个明确的Enumerable.Join更具可读性: “测试老客户名单中的姓氏投影是否与新客户名单中的姓氏投影具有相同的内容”,这与问题陈述非常接近。

+0

这当然是一个很好的选择。我希望有一个“IntersectBy”标准的LINQ操作符,所以我们可以做'OldCustomerList.IntersectBy(NewCustomerList,x => x.Surname)'... – 2010-09-26 08:29:50

相关问题