2

I have a query below. although can anyone point out what "from p" means? and also "var r"?

DataClasses1DataContext db = new DataClasses1DataContext(); 
            var r = from p in db.Products 
                    where p.UnitPrice > 15 // If unit price is greater than 15...
                    select p; // select entries
James
  • 257
  • 2
  • 3
  • 5

3 Answers3

3

r is the composed query - an IQueryable<Product> or similar; note the query has not yet executed - it is just a pending query. var means "compiler, figure out the type of r from the expression on the right". You could have stated it explicitly in this case, but not all. But it wouldn't add any value, so var is fine.

p is a convenience marker for each product; the query is "for each product (p), restricting to those with unit price greater than 15 (where p > 15), select that product (select p) as a result.

Ultimately this compiles as:

IQueryable<Product> r =
    db.Products.Where(p => p.UnitPrice > 15);

(in this case, a final .Select(p => p) is omitted by the compiler, but with a non-trivial projection, or a trivial query, the .Select(...) is retained)

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
1

The p means each specific item in the collection referenced (db.Products). See from on MSDN.

var is syntactic sugar - it resolves to the type returned from the LINQ query, assigning the type to the variable r. See var on MSDN.

For better understanding of LINQ, I suggest reading through 101 LINQ Samples.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
0

from p means any record from db.Product and var r means the collection of p

overall whole statements means give me all those records(p) from db.Products where p.UnitPrice is greater than 15

see this question to know more about var

Community
  • 1
  • 1
Haris Hasan
  • 29,856
  • 10
  • 92
  • 122