Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is wrong with this statement below

What is wrong with this statment below? I get "; expected" when run it in LinqPad with language setting to "C# Statement".

from p in Products where p.UnitPrice > 50 select new {p.ProductID };

Now seem like if I assign it to any var; I don't get any error. But what I find confusing is the statement below works fine and give me results back although I don't assign it to any variable. Any ideas?

    from p in Products
let spanishOrders = p.OrderDetails.Where ( o=> o.Order.ShipCountry == "Spain")
where spanishOrders.Any()
group new
{
    p.ProductName,
    Orders = spanishOrders.Count(),
    spanishOrders
}
by p.Category.CategoryName

EDIT: It was my bad actually i couldn't run the second example without assigning it to a variable.

like image 826
Silverlight Student Avatar asked Nov 19 '25 03:11

Silverlight Student


2 Answers

LINQ Query expressions are not legal statements in C#. You need to use the expression in a valid statement.

For example, you could use the expression as the right-hand side of an assignment statement:

var expensiveProductIds = from p in Products
                          where p.UnitPrice > 50 
                          select new { p.ProductID };

It does appears to me like you don't really understand what LINQ is all about. What did you expect your naked query expression to do?

EDIT: Take a look at Alex Moore's answer for how to get this to work in LINQPad.

By the way, here's a way to get the results of the query written to console if you still want to stick with the "C# Statement(s)" mode:

var expensiveProductIds = from p in Products
                          where p.UnitPrice > 50 
                          select new { p.ProductID };

expensiveProductIds.Dump();
like image 142
Ani Avatar answered Nov 20 '25 16:11

Ani


If you are using "C# Expression" as the Language in the LinqPad language drop down, you have to drop the semi-colon because it's just an expression:

from p in Products where p.UnitPrice > 50 select new {p.ProductID }

If you are using "C# Statement(s)" as the language, you will have to write it out like regular C# code:

var x = (from p in Products where p.UnitPrice > 50 select new {p.ProductID });

LINQPad lets you test both ways, because some queries are easier when you get the statements out of the way.

like image 26
Alex Moore Avatar answered Nov 20 '25 17:11

Alex Moore