如何在 LINQ 中编写子选择。
如果我有一个客户列表和一个订单列表,我想要所有没有订单的客户。
这是我的伪代码尝试:
var res = from c in customers
where c.CustomerID ! in (from o in orders select o.CustomerID)
select c
如何在 LINQ 中编写子选择。
如果我有一个客户列表和一个订单列表,我想要所有没有订单的客户。
这是我的伪代码尝试:
var res = from c in customers
where c.CustomerID ! in (from o in orders select o.CustomerID)
select c
怎么样:
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 还是其他东西?不同的口味可能有不同的“最佳”方式
如果这是数据库支持的,请尝试使用导航属性(如果您定义了它们):
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]
))
哪个做得很好。
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();
var res = (from c in orders where c.CustomerID == null
select c.Customers).ToList();
或使除外()