如何在LINQ中编写子选择。
如果我有一个客户列表和一份订单列表,我希望所有没有订单的客户。
这是我的伪代码尝试:
var res = from c in customers
where c.CustomerID ! in (from o in orders select o.CustomerID)
select c
答案 0 :(得分:23)
怎么样:
var res = from c in customers
where !orders.Select(o => o.CustomerID).Contains(c.CustomerID)
select c;
另一种选择是使用:
var res = from c in customers
join o in orders
on c.CustomerID equals o.customerID
into customerOrders
where customerOrders.Count() == 0
select c;
您使用的是LINQ to SQL还是别的什么,顺便问一下?不同的口味可能有不同的“最佳”方式
答案 1 :(得分:7)
如果这是由数据库支持的,请尝试使用导航属性(如果已定义它们):
var res = from c in customers
where !c.Orders.Any()
select c;
在Northwind上,这会生成TSQL:
SELECT /* columns snipped */
FROM [dbo].[Customers] AS [t0]
WHERE NOT (EXISTS(
SELECT NULL AS [EMPTY]
FROM [dbo].[Orders] AS [t1]
WHERE [t1].[CustomerID] = [t0].[CustomerID]
))
这项工作做得很好。
答案 2 :(得分:-1)
var result = (from planinfo in db.mst_pointplan_info
join entityType in db.mst_entity_type
on planinfo.entityId equals entityType.id
where planinfo.entityId == entityId
&& planinfo.is_deleted != true
&& planinfo.system_id == systemId
&& entityType.enity_enum_id == entityId
group planinfo by planinfo.package_id into gplan
select new PackagePointRangeConfigurationResult
{
Result = (from planinfo in gplan
select new PackagePointRangeResult
{
PackageId = planinfo.package_id,
PointPlanInfo = (from pointPlanInfo in gplan
select new PointPlanInfo
{
StartRange = planinfo.start_range,
EndRange = planinfo.end_range,
IsDiscountAndChargeInPer = planinfo.is_discount_and_charge_in_per,
Discount = planinfo.discount,
ServiceCharge = planinfo.servicecharge,
AtonMerchantShare = planinfo.aton_merchant_share,
CommunityShare = planinfo.community_share
}).ToList()
}).ToList()
}).FirstOrDefault();
答案 3 :(得分:-2)
var res = (from c in orders where c.CustomerID == null
select c.Customers).ToList();
或Make Except()