I have yet to find a good way to represent an IN clause in Linq, but I found this yesterday and kind of liked it. Mind you, I’ve used this only on two lists, not database involved. Will check what it does on the database call later.
Anyhow, I needed a way to check if the records in one list are the same as the other. I’m sure there are a billion ways to do this, but I wanted a Linq way. I stumbled onto this idea when looking for a solution to something else. Basically I have two lists of users and a user contains a UserID. listOne and listTwo are both List<User>.
var query = from listOneUser in listOne where !( from listTwoUser in listTwo select listTwoUser.UserID ).Contains(listOneUser.UserID) select listOneUser;
I select all the IDs from the second list and then see if the first list has any users that don’t exist in the second list. If this query gives me a list with a count greater then 0, I know that list one has at least one different item. Again, this isn’t bullet proof, just a way to show the kind of IN clause.
2 thoughts on “Sub Select and IN Clause With Linq”
Comments are closed.