2009-02-09 2 views
14

어떻게 LINQ에 하위 선택을 작성합니까?Linq Sub-Select

고객 목록과 주문 목록이있는 경우 주문이없는 모든 고객이 필요합니다.

이 내 의사 코드 시도 :이 데이터베이스 백업 인 경우

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

답변

22

를 제외하고

+0

가독성 측면에서 보면 Count() 대신 Any()가 사용되지 않고 있습니까? Bill Wagner의보다 효과적인 C#을 읽었으며 이것이 권장 사항 중 하나였습니다. –

+2

예, 가능합니다. 그것을하는 많은 방법. 아마 Any()의 반대 인 Empty() 또는 None() 확장 메서드를 사용하는 것이 좋을 것입니다 ... –

+0

그래, 좋은 생각이야. –

7

, (당신이 그들을 정의 된 경우) 탐색 속성을 사용하십시오 :

하여 Northwind에
var res = from c in customers 
      where !c.Orders.Any() 
      select c; 

는, 이것이 발생 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 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; 

당신이 SQL 또는 뭔가에 LINQ를 사용하고, BTW에 대해 어떻게()

-2
var res = (from c in orders where c.CustomerID == null 
       select c.Customers).ToList(); 

또는 확인 ? 다른 풍미가 다른 최상의 방법을 가지고 있습니다.

-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(); 
+1

설명 추가 –