2

I'm trying to find a good reference to help me convert this TSQL statement to Linq:

EXAMPLE:

SELECT * FROM Categories WHERE ProductID IN (SELECT ProductID FROM ProductCategories WHERE CatID = 23)

I can't find anywhere that references how to do the WHERE "IN" part.

RichC
  • 7,829
  • 21
  • 85
  • 149

3 Answers3

2

While it's not exactly a TSQL to LINQ reference, I have found the 101 LINQ Samples page on MSDN helpful for this purpose.

See also this related question

Community
  • 1
  • 1
Eric King
  • 11,594
  • 5
  • 43
  • 53
  • Thanks - is this: http://msdn.microsoft.com/en-us/vcsharp/aa336761.aspx#intersect2 what I'm looking for? TSQL "IN" = Linq "Intersect"? – RichC Feb 14 '09 at 03:13
  • Ooops - I just now saw your "this related question" which gave me the answer I was looking for. – RichC Feb 14 '09 at 03:34
1

See if this works:

var qry = from c in Categories
          where (from pc in ProductCategories where pc.CatID = 23 select pc.ProductID).Contains(c.ProductID)
          select c;

I don't know if there is a direct translation of the IN WHERE part in LinqToSQL (didn't found any reference) but I replaced that with a Contains.

bruno conde
  • 47,767
  • 15
  • 98
  • 117
1

Using extension methods...

var productIDs = context.ProductCategories
                        .Where( c => c.CatID == 23 )
                        .Select( c => c.ProductID );
var categories = context.Categories
                        .Where( c => productIDS.Contains( c => c.ProductID ) );

EDIT: 101 Linq Samples is a pretty good reference for simple things. For more complicated stuff I find that I usually have to resort to Google. FYI, if you want to search StackOverflow, I've found that it works better to use google and specify site: stackoverflow.com. YMMV.

tvanfosson
  • 524,688
  • 99
  • 697
  • 795