Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How do I write a sub-select in LINQ.

If I have a list of customers and a list of orders I want all the customers that have no orders.

This is my pseudo code attempt:

    var  res = from c in customers 
where c.CustomerID ! in (from o in orders select o.CustomerID) 
select c
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
224 views
Welcome To Ask or Share your Answers For Others

1 Answer

How about:

var res = from c in customers 
          where !orders.Select(o => o.CustomerID).Contains(c.CustomerID)
          select c;

Another option is to use:

var res = from c in customers
          join o in orders 
               on c.CustomerID equals o.customerID 
               into customerOrders
          where customerOrders.Count() == 0
          select c;

Are you using LINQ to SQL or something else, btw? Different flavours may have different "best" ways of doing it


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...