Tuesday, March 24, 2009

LINQ statement similar to SQL "In" statement

This is a very interesting LINQ feature I've stumbled across in my day to day work.

I can't quite post my work here but essentially, it is quite possible to imitate the "IN" statement in SQL.

What I meant by the "IN" query is for example;

SELECT * FROM [table]
WHERE id IN (1, 2, 3)

Using the extension method of "Contains" method, we achieve the SQL "In" method using LINQ. See below.

Have 2 list.
Eg: listOfElements1, listOfElements2

Depending on which list you would like to obtain the information from, perform a LINQ query on that list. For the purpose of this example, I am going to be using the LINQ query on the 1st list of elements.

VB Code
Dim linqToTest = From le1 In listOfElements1.ToArray() _
Where listOfElements2.Contains(le1.[elementName]) _
Select le1

A point to note is that 1 of my list is a list of primitive variables (listOfElements2) and the other (listOfElements1) is a list of objects.

Should you require joining of 2 list of similar types, primitive variables list with primitive variables list of the same type or list of objects that have 1 similar property, the LINQ "intersect" function should suffice.


References:
1. Rob Conery's blog; Wekeroad

No comments:

Post a Comment