Follow up to my “Intro to LINQ” session at the MS TechDays

As promised during my session, I’m going to be addressing every unanswered question from my session in this post (we just didn’t have much time to take many questions…). So here we go!

“…don’t forget to mention how to update/delete/add to the database using LINQ”

Those operations are taken care of by the “DataContext” object. That object keeps track of changes made to the result set you get back from the query. So you make changes to the objects, and whenever you’re done, make a call to SubmitChanges() on the datacontext object.

“Is type inference related somehow to dynamic language features, javascript, and stuff?” and “isn’t c# losing its strongly typed features with LINQ?”

Nope, not at all. Dynamic language features aren’t checked during compiled time. The type inference feature in C# does check typing information during compile time. When we use type inference we must assign a value to the variable in the line where we declare it, because that’s the only way the compiler is able to infer the type based on the value being assigned to the variable. Also, an anonymous type is a strongly typed object, even though we don’t define those classes ourselves; the compiler will generate IL code for those types based on how we’ve initialized the type (what property names and type of values we’ve assigned to them).

“Can you have a return result (vs. void) in the foreach delegate/lambda?”

Not in the ForEach method, no. That method takes in an Action<T> delegate, which returns void. That method is specifically designed to go through every item in the list and perform some sort of action using the item. There are methods that take either a Function or Predicate delegate, which do have a return type. If you look up those delegates you’ll find examples of using it.

“Can the .dbml file be used to build up the class of the underlying schema; or is there a better approach; or is it off base to want to know some much about the actual underlying database structure (break separation of concerns). What should one do to get a deep sense of the database schema?”

I’m not entirely sure I understand the questions, but let me try to clarify that: the dbml file is a file containing classes that model the underlying database. For example, for a given “Northwind” database, you’ll have a “NorthwindDataContext” class, which in turn will have Customers and Products properties. Those properties are a kind of collection of Customer and Product types, which are classes that model those tables in the database, and therefore, have properties that map to columns in those tables.

You should probably do some research on Object-Relational Mappers (ORM), and things like NHibernate, in order to get a good understanding of separation of concerns regarding the impedance mismatch between objects and databases.

“Why is “foreach” always underlined in blue when you type it?

I’m guessing you’re asking the about the connector lines between the braces. That’s a CodeRush feature.

“Is LINQ working with WMI queries?”

I haven’t messed with that myself, but I’ve found this for you: LINQ to WMI. I hope this helps. 

“You mentioned about the same performance using LINQ vs. traditional foreach. Are there circumstances where performance does become an issue?” and a related question “is that right that you said there is virtually no performance difference between using LINQ, and doing it manually with for loops?”

Correct. LINQ ultimately performs a foreach, so whether you do the foreach yourself, or let LINQ do it, performance is about the same. However, check the answer to the next question. There’s the Hooked on LINQ website.

“Is there a performance gain in using LINQ"?”

Not currently. However, there will be when the next version of Visual Studio comes out. We’ll get what’s called “parallel extensions”. With that will be able to just add a call to .AsParallel() to our query expression, which will cause the query to have items processed in parallel in multi-core machines (which is the case of pretty much every new computer).

“Do you have any good reference for more LINQ?”

I like the chapters in this book covering LINQ, because it explains things under the hood: C# in Depth. I’ve heard great comments about LINQ in Action, but haven’t had a chance to check it out myself.

There’s the Hooked on LINQ website, and also a few blog posts of mine here, here, here, and here.

“If the query is only invoked when it is referenced first time, only every time it is reference; hence is it important to cache it if it is to be referenced multiple times?

When the query expression is defined, and query does not get executed. Every time there’s a foreach against the query expression, it does get executed. If you need to run multiple foreach’s on the query, but don’t want the query to be executed every time, just call .ToList() on the query expression, which is going to execute the query once, put its results into a List object, and then you can iterate through that list as many times as needed.

“Can LINQ query a database other than SQL Server?”

LINQ to SQL is specific to SQL Server. LINQ to Entities, on the other hand, uses the Entity Framework, which can be targeted to databases other than SQL Server.

“Why is LINQ written in reverse order?”

I assume you’re referring to the fact that in traditional SQL (such as T-SQL), “select” comes before “from”, whereas in LINQ, “from” comes first, and “select” comes last. That’s also something that bothered me on the beginning: I had been working with T-SQL and the built-in SQL that Visual FoxPro had had for so many years, and then I was faced with this weird thing that had a “select” coming at the end. Once I saw the reasoning behind that decision, I started seeing old SQL as the “reversed” one.  🙂

I’ll explain. First, think of Intellisense support. We type “select “, and then what? How would any tool know what list of columns to display so I could pick from it? The list could show all tables with their related columns, but what if we are also going to have JOINs in that query? Until we’ve actually provided the FROM and the JOIN parts of our query, it’s impossible for Intellisense to know what list to show for the “SELECT” part.

Second, coming to think about it, SELECT coming first doesn’t even make sense for somebody reading the code. If we think about what we want the results of our query to look like, the following thought seems to make sense: “first I need to know from which main source I’ll be retrieving the data, then I need to know whether I need to join that source with others, then I need to know how I want that data filtered, then I need to know how I need the data grouped and/or ordered. And finally, out of all of that, I need to finally decide the shape of the results, such as which columns I want, or even whether the product of my query is going to be a more complex, hierarchical object”.

In order words, the “select” can only be satisfied at the end of the expression, once all the other things have been established.

I have an example from the real world that always comes to my mind when I think about the whole “from/select” in LINQ. In Brazil, the address format looks like this:

Rua Marcos Moura, 243
Some City, State – 12345

Notice that the first thing we see is the name of the street, or avenue, or whatever, and only after that we get to see the number. I think that makes a lot more sense than the address format in the U.S. Why? Let’s say somebody is about to die, and she asks you to deliver a very important message to somebody. She tells you the message, and then starts saying the address: “they live at 987…”, and then bang! she dies. Now what the heck do you do with just that number? We can knock at the door of every place whose number is 987.

On the other hand, if the person said “They live at Whatever Av…”, and then dies, at least you could narrow the number of doors you’d have to knock at in order to deliver the message.  🙂

“superb, superb – bravo – sat through 2 hours of a talk this past weekend on the same concepts. Claudio’s explanation is far superior”

That’s flattering. Thank you. It’s always great to know I’ve been able to clarify something to somebody.  🙂

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: