So even though I usually like to think of myself as someone that is “in the know” of the latest and greatest technologies, lately I’ve been too busy to experiment with newer stuff. So about a month ago I decided to embark on a LINQ learning path, trying to learn as much about it as I can on my spare time (the small amount that I have), and also a project came up where I can make use of these new skills of mine. I’ve worked with data my entire career, even for my Senior Design project in college, I was the guy in charge of the data (schema, retrieval, updating it, etc), I like data and feel very comfortable dealing with it. LINQ is such a huge change for all developers, it allows us do so much more than we could’ve ever done before with it. And I’m not just talking about what you can do with LINQ to SQL or LINQ to XML, I’m talking about the plain vanilla LINQ. WOW!! There so much power and potential and it will take us to places that many people hadn’t thought of before.
So anyway I’ll update some of the cool things that I find in my LINQ venture. Here’s one…it took me a while to figure this out the other day. I needed to be able to do an “IN” clause using LINQ, something that in SQL would go like this:
SELECT * FROM myTable
WHERE myColumn IN (‘value1’, ‘value2’, ‘value3’)
This is how you do it in LINQ:
using (DataContext _DB = new DataContext(SqlConnection)) { string[] criteria = new string[] { "test", "test2", "test3" }; var values = (from m in _DB.myTable where criteria.Contains(m.myColumn) select m); }
It feels a bit weird at first, but then when you think about it, you have to think backwards in LINQ. So you are checking whether the values in the database are contained by your string array, rather than the other way around. Running profiler, you can see that the generated SQL is what was expected.