Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ - Using Select - understanding select

Tags:

c#

linq

.net-4.0

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>?

like image 760
P.Brian.Mackey Avatar asked Dec 21 '22 13:12

P.Brian.Mackey


2 Answers

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;
like image 191
Tim Avatar answered Jan 02 '23 13:01

Tim


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.

like image 42
usr Avatar answered Jan 02 '23 11:01

usr