P.Brian.Mackey
P.Brian.Mackey

Reputation: 44275

LINQ - Using Select - understanding select

I find LINQ a little difficult to wrap my head around. I like the concept and believe it has lots of potential. But, after writing so much SQL the syntax is just not easy for me to swallow.

A. What is the deal with multiple ways to select?

I see that I am able to create a context and perform a Select() using a method.

context.Table.Select(lamba expression);

ok...Why would I use this? How does it compare to (or does it) this type of select?

var returnVal = from o in context.Table
                orderby o.Column
                select o;

B. Please explain the variable nature of

**from X** in context.Table

Why do we stick a seemingly arbitrarily named variable here? Shouldn't this be a known type of type <Table>?

Upvotes: 4

Views: 10251

Answers (3)

Tim
Tim

Reputation: 15237

So...

var returnVal = context.Table.Select(o => o);

and

var returnVal = from o in context.Table
                select o;

are the same. In the second case, C# just has nice syntactic sugar to give you something closer to normal SQL syntax. Notice I removed the orderby from your second query. If you wanted that in there, then the first one would become:

var returnVal = context.Table.OrderBy(o => o.Column).Select(o => o);

As for your last question... we're not sticking an arbitrarily named variable here. We're giving a name to each row so that we can reference it later on in the statement. It is implicitly typed because the system knows what type Table contains.

In response to your comment, I wanted to add one more thought. You mentioned things getting nasty with the normal method calls. It really can. Here's a simple example where its immediately much cleaner (at least, if you're used to SQL syntax) in the LINQ syntax:

var returnVal = context.Table.OrderBy(o => o.Column1)
                             .ThenBy(o => o.Column2)
                             .ThenBy(o => o.Column3)
                             .Select(o => o);

versus

var returnVal = from o in context.Table
                orderby o.Column1, o.Column2, o.Column3
                select o;

Upvotes: 5

usr
usr

Reputation: 171178

A: this is the same. The compiler transforms the query expression to method calls. Exactly the same.

B: The x is the same as in foreach(var X in context.Table). You define a name for an individual element of the table/sequence.

Upvotes: 5

Ry-
Ry-

Reputation: 224904

In B, X's type is implicit. You could just as easily do something like:

from Row x in context.Table

and it would be the same. In A, there isn't any difference between using a lambda and the equivalent full-LINQ syntax, except that you would never do .Select(x => x). It's for transforming items. Say you had a list of integers, .Select(x => x * x) would return the square of each of them.

Upvotes: 1

Related Questions