3

A sample linq query from MSDN:

var expensiveInStockProducts =
    from p in products
    where p.UnitsInStock > 0 && p.UnitPrice > 3.00M
    select p;

Does this query select EVERY column from the database table immediately, or does it return some sort of pointer that retieves the actual column data on demand? ie. If there are 50 columns in my table and I only use a single p.UnitsInStock in my actual code, then am I retrieving 50 times more data than I expected?

1
  • 2
    Are you talking about columns or rows? It seems like you're talking about rows, but I'm not sure. Commented Nov 9, 2010 at 18:17

2 Answers 2

3

if you debugged that then you would probably see every column in your products table in the SELECT ... portion of the query

if you did select p.UnitsInStock you would only see that in the SELECT ... portion of the query.

So to answer your question, yes, it does select every column unless you specify what you want or dump the selection into an anonymous object like so:

var expensiveInStockProducts =
    from p in products
    where p.UnitsInStock > 0 && p.UnitPrice > 3.00M
    select new { p.UnitsInStock, p.SomeOtherColumn }
Sign up to request clarification or add additional context in comments.

2 Comments

Ok, so short answer is that doing a broad-brush "select p" is a bad move if most of that column data is not needed?
yes, if you only want a single column, then only select p.ColumnName. If you need multiple columns, create a new object on the fly and get what columns you want.
1

I would advise using LINQPad if you want to see the generated SQL it really helps to visualise, just to help with what you want you can (if you only need the data locally) use an anonymous object or select into a concrete class within your applications model,

so

Anonymous

var expensiveInStockProducts =
from p in products
where p.UnitsInStock > 0 && p.UnitPrice > 3.00M
select new {
           p.ColumnIWant1,
           p.ColumnIWant2
          };

or for a concrete class

var expensiveInStockProducts =
from p in products
where p.UnitsInStock > 0 && p.UnitPrice > 3.00M
select new MyClass() {
          ColumnIWantAsField1 = p.ColumnIWant1,
          ColumnIWantAsField2 = p.ColumnIWant2
          };

1 Comment

This got helpful to me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.