您将如何使用LINQ进行“不参加”查询?

本文翻译自:How would you do a “not in” query with LINQ?

I have two collections which have property Email in both collections. 我有两个集合,两个集合中都有“ Email属性。 I need to get a list of the items in the first list where Email does not exist in the second list. 我需要获取第一个列表中的项目列表,而第二个列表中不存在Email With SQL I would just use "not in", but I do not know the equivalent in LINQ. 使用SQL时,我只会使用“ not in”,但我不知道LINQ中的等效项。 How is that done? 怎么做?

So far I have a join, like... 到目前为止,我已经加入了,例如...

var matches = from item1 in list1
join item2 in list2 on item1.Email equals item2.Email
select new { Email = list1.Email };

But I cannot join since I need the difference and the join would fail. 但是我无法加入,因为我需要区别,加入会失败。 I need some way of using Contains or Exists I believe. 我需要某种相信使用的包含或存在方式。 I just have not found an example to do that yet. 我只是还没有找到执行此操作的示例。


#1楼

参考:https://stackoom.com/question/loN/您将如何使用LINQ进行-不参加-查询


#2楼

I don't know if this will help you but.. 我不知道这是否对您有帮助。

NorthwindDataContext dc = new NorthwindDataContext();    
dc.Log = Console.Out;

var query =    
    from c in dc.Customers    
    where !(from o in dc.Orders    
            select o.CustomerID)    
           .Contains(c.CustomerID)    
    select c;

foreach (var c in query) Console.WriteLine( c );

from The NOT IN clause in LINQ to SQL by Marco Russo Marco Russo的 LINQ中的NOT IN子句到SQL


#3楼

var secondEmails = (from item in list2
                    select new { Email = item.Email }
                   ).ToList();

var matches = from item in list1
              where !secondEmails.Contains(item.Email)
              select new {Email = item.Email};

#4楼

You want the Except operator. 您需要Except运算符。

var answer = list1.Except(list2);

Better explanation here: http://blogs.msdn.com/charlie/archive/2008/07/12/the-linq-set-operators.aspx 更好的解释在这里: http : //blogs.msdn.com/charlie/archive/2008/07/12/the-linq-set-operators.aspx

NOTE: This technique works best for primitive types only, since you have to implement an IEqualityComparer to use the Except method with complex types. 注意:此技术仅对基本类型最有效,因为您必须实现IEqualityComparer才能将Except方法与复杂类型一起使用。


#5楼

Example using List of int for simplicity. 为了简单起见,使用int列表的示例。

List<int> list1 = new List<int>();
// fill data
List<int> list2 = new List<int>();
// fill data

var results = from i in list1
              where !list2.Contains(i)
              select i;

foreach (var result in results)
    Console.WriteLine(result.ToString());

#6楼

items in the first list where the Email does not exist in the second list. 第一个列表中的项目,而第二个列表中不存在电子邮件。

from item1 in List1
where !(list2.Any(item2 => item2.Email == item1.Email))
select item1;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值