That may be old news to some, but the it seems like every time I pull LINQ out of my toolbox I am more and more impressed with it. I have a list of favorite interview questions I like to ask a candidate, and they are mostly centered around conversation as opposed to test questions. One of my favorite interview questions to ask someone is “What is your favorite thing about .NET?". There is no right or wrong answer there, but I am looking for an answer that shows some kind of passion. If I were to answer my own question, for me it used to be reflection, but now my answer would be LINQ. It is awesome to have a set based tool in your kit.
Since LINQ seems to teach me something every time I use it, this post was prompted by what I thought was a pretty cool query. Say you were given an collection object called Dealerships, and there is a shared method on a Dealership a list that contains all of the valid makes of car that the Dealership is allowed to sell. Then you have a user in UserRequestedObject that has requested to see the Dealerships that are possible matches for the makes he/she wants to buy.
The data would look something like this:
| | Dealerships | | | | |
| | Dealership1 | Dealership2 | Dealership3 | Dealership4 | Dealership 5 |
| | BMW | BMW | VW | Porsche | Ford |
| | Maserati | | Audi | Lamborghini | |
| | Land Rover | | | | |
| | UserRequestedObject |
| | BMW |
| | Porsche |
So, one way to find the dealerships the user is asking for is you could write a query like this :
Dim commonDealerships = (From t In dealerships Where _
(From p In UserRequestedObject Select p.MakeOfCar).Any _
(Function(u) GetValidMakesForDealership(t).Contains(u)))
Which will return you Dealerships 1, 2 and 4, and is seriously cool stuff if you ask me.
In addition, if you have an object that is a collection that contains another object that is a collection, like this:
| |
Dealership |
Cars |
|
|
| |
Dealership1 |
Car1 |
Car2 |
|
| |
Make |
BMW |
BMW |
|
| |
Model |
M3 |
M5 |
|
| |
Year |
1997 |
2000 |
|
| |
|
|
|
|
| |
Dealership2 |
Car1 |
Car2 |
Car3 |
| |
Make |
BMW |
Audi |
BMW |
| |
Model |
540 |
S4 |
M3 |
| |
Year |
2001 |
2005 |
1997 |
If a user requested to see all dealerships that have a 1997 BMW M3, you could write a query like this:
Dim m3Dealers = (From t In dealerships Where _
(From p In t.Cars Select p.Make, p.Model, p.Year).All _
(Function(u) u.Make = requestedMake AndAlso u.Model = requestedModel AndAlso u.Year = requestedYear))
Nested Loops no more! This effectively gives you all parent rows that have children that are an exact match to the key you passed in. I understand that under the hood this is doing the same thing as a nested loop, but if you can think in set based syntax, sometimes that is the best way to solve the problem. Very useful!
Technorati Tags:
LINQ,
.NET