Thursday, March 1, 2012

Linq with in() the where clause

I recently needed to do a select with a in() clause, so T sql needed to be

   1: select * from ProductReturns pr inner join LinesExpected le on(pr.ProductReturnID=le.ProductReturnID)
   2: where pr.ProductReturnID in(4, 3, 9, 10, 27)


To accomplish this I used an array and did a “contains” within it.  In C# looks like following



   1: int[] numbers = new int[5] {4, 3, 9, 10, 27};
   2:  
   3:  
   4: var query = from i in ProductReturns
   5:             from c in LinesExpecteds
   6:             where i.ProductReturnID == c.ProductReturnID
   7:             && numbers.Contains(i.ProductReturnID)
   8:             select i;
   9:  
  10: var items = query.ToList();


Resulting SQL is



   1: SELECT 
   2: [Extent1].[ProductReturnID] AS [ProductReturnID], 
   3: [Extent1].[ProductReturnIDFull] AS [ProductReturnIDFull], 
   4: [Extent1].[ReturnStatusID] AS [ReturnStatusID], 
   5: [Extent1].[ReturnSystemStatusID] AS [ReturnSystemStatusID], 
   6: [Extent1].[CustID] AS [CustID], 
   7: [Extent1].[ContactName] AS [ContactName], 
   8: [Extent1].[ContactPhone] AS [ContactPhone], 
   9: [Extent1].[ContactEmail] AS [ContactEmail], 
  10: [Extent1].[ShipFromAddress1] AS [ShipFromAddress1], 
  11: [Extent1].[ShipFromAddress2] AS [ShipFromAddress2], 
  12: [Extent1].[ShipFromCity] AS [ShipFromCity], 
  13: [Extent1].[ShipFromState] AS [ShipFromState], 
  14: [Extent1].[ShipFromZipCode] AS [ShipFromZipCode], 
  15: [Extent1].[ReturnWarehouse] AS [ReturnWarehouse], 
  16: [Extent1].[PrepaidLabelCount] AS [PrepaidLabelCount], 
  17: [Extent1].[PrepaidLabelPDF] AS [PrepaidLabelPDF], 
  18: [Extent1].[PalletCountCarrier] AS [PalletCountCarrier], 
  19: [Extent1].[PalletCountTotalReturn] AS [PalletCountTotalReturn], 
  20: [Extent1].[PickUpDate] AS [PickUpDate], 
  21: [Extent1].[PickUpTime] AS [PickUpTime], 
  22: [Extent1].[IsLiftGateRequired] AS [IsLiftGateRequired], 
  23: [Extent1].[IsShrinkWrapRequired] AS [IsShrinkWrapRequired], 
  24: [Extent1].[IsPalletJackRequired] AS [IsPalletJackRequired], 
  25: [Extent1].[IsRestockingFee] AS [IsRestockingFee], 
  26: [Extent1].[RestockingFeeWaivedComment] AS [RestockingFeeWaivedComment], 
  27: [Extent1].[TotalPrepaidWeight] AS [TotalPrepaidWeight], 
  28: [Extent1].[TotalWeight] AS [TotalWeight], 
  29: [Extent1].[UpdateCounter] AS [UpdateCounter], 
  30: [Extent1].[Active] AS [Active], 
  31: [Extent1].[CreateDate] AS [CreateDate], 
  32: [Extent1].[CreatedBy] AS [CreatedBy], 
  33: [Extent1].[ModifiedDate] AS [ModifiedDate], 
  34: [Extent1].[ModifiedBy] AS [ModifiedBy]
  35: FROM  [dbo].[ProductReturns] AS [Extent1]
  36: INNER JOIN [dbo].[LinesExpected] AS [Extent2] ON [Extent1].[ProductReturnID] = [Extent2].[ProductReturnID]
  37: WHERE [Extent1].[ProductReturnID] IN (4,3,9,10,27)

No comments:

Post a Comment