I was looking over some LINQ examples, and was thereby reminded they are supposed to have a "select" clause at the end.
But I have a LINQ that's working and has no "Select":
public IEnumerable<InventoryItem> Get(string ID, int packSize, int CountToFetch)
{
return inventoryItems
.Where(i => (i.Id.CompareTo(ID) == 0 && i.PackSize > packSize) || i.Id.CompareTo(ID) > 0)
.OrderBy(i => i.Id)
.ThenBy(i => i.PackSize)
.Take(CountToFetch)
.ToList();
}
Is this because:
(a) select is not really necessary?
(b) Take() is doing the "select"
(c) ToList() is doing the "select"
Truth be told, this was working before I added the "ToList()" also... so it seems LINQ is quite permissive/lax in what it allows one to get away with.
Also, in the LINQ I'm using, I think the OrderBy and ThenBy are redundant, because the SQL query used to populate inventoryItems already has an ORDER BY ID, PackSize clause. Am I right (that the .OrderBy() and .ThenBy() are unnecessary)?
Linq statements do in fact need a select clause (or other clauses, such as a group by). However, you're not using Linq syntax, you're using the Linq Enumerable extension methods, which all (for the most part) return IEnumerable<T>. Therefore, they do not need the Select operator.
var result = from item in source
where item.Value > 5
select item;
Is exactly the same as
var result = source.Where(item => item.Value > 5);
And for completeness:
var result = from item in source
where item.Value > 5
select item.Value;
Is exactly the same as
var result = source.Where(item => item.Value > 5)
.Select(item => item.Value);
Linq statements (Linq syntax statements) need a special clause at the end to signify what the result of the query should be. Without a select, group by, or other selection clause, the syntax is incomplete, and the compiler does not know how to change the expression into the appropriate extension methods (which is what Linq syntax actually gets compiled to).
As far as ToList goes, that's one of the Enumerable extension methods that does not return an IEnumerable<t>, but instead a List<T>. When you use ToList or ToArray the Enumerable is enumerated immediately and converted to a list or array. This is useful if your query is complex and you need to enumerate the results multiple times without running the query multiple times).
You only use select when you want to project your object into a different type..
if you had a list that contains an object with an ID property that was an int
var newList = items.Select(i => i.ID);
newList would be an IEnumerable<int>
NB.
A common mistake is to mix up a Select with a Where.
items.Where(i => i.ID == 1); returns an IEnumerable<item>
items.Select(i => i.ID == 1); returns an IEnumerable<bool>
as the Select projects each item into the result of the function passed in..
Related
I have a linq query which I want to add some additional, optional WHERE conditions to using LinqKit Predicate Builder. However, I an struggling to get the additional predicate to work
This is my initial query:
var query = (from OP in ctx.OrganisationProducts
where OP.OrganisationID == orgID
orderby OP.Product.Name, OP.Product.VersionName
select OP).Include("Product");
As you can see, there is JOIN in there.
I then wish to add additional predicates if required:
if(!includeDisabledP42Admin || !includeDisabledOrgAdmin)
{
var pred = PredicateBuilder.True<OrganisationProduct>();
if (!includeDisabledP42Admin)
pred.And(op => op.Enabled);
if (!includeDisabledOrgAdmin)
pred.And(op => op.AccessLevel == "NA" || op.AccessLevel == "NU");
query = query.Where(pred);
}
However, the generated SQL is unchanged and the query returns the same number of rows.
I thought I might have had to do the Expand conversion as so:
query = query.AsExpandable().Where(pred);
But this causes a runtime error.
I think the issue is the fact that I am adding the predicate to a query that is already no longer a pure OrganisationProduct object, however I would like advise on how I insert my predicate at the right place.
Thanks and all :-)
You have to assign the return value of And to the predicate:
pred = pred.And(op => op.Enabled);
Side note: you may like this predicate builder that works without Expand/AsExpandable, but has the same syntax.
See two functionally identical queries below, sql and lambda version:
from a in Lines.AsEnumerable()
where a.LineId == SomeGuid
select a
-
Lines.AsEnumerable()
.Where(a => a.LineId == SomeGuid)
.Select(a => a)
Both queries will be translated into SQL that doesn't have WHERE statement, something like
SELECT * FROM Line
In lambda, I can conveniently put AsEnumerable after Where clause and resulting SQL will have WHERE clause. So, lambda query would be like:
Lines
.Where(a => a.LineId == SomeGuid)
.AsEnumerable()
.Select(a => a)
And resulting SQL is SELECT * FROM Line WHERE LineId = #param
Question:
How do I do this using Linq SQL syntax? In other words, I would like my resulting SQL statement to have WHERE clause. I want to avoid pulling all records from the table Line. I tried to put AsEnumerable on different places within the query, but I failed to make it work.
EDIT:
In simple statements putting AsEnumerable on the end will work, but if you use projection, then EF complains (NotSupported Exception: Complex type can't be constructed ...)
So,
(from a in Lines
where a.LineId == SomeGuid
select new Line
{
LineId = a.LineId
}).AsEnumerable()
Won't work
You will simply do this:
var query (from a in context.Lines
where a.LineId == SomeGuid
select a).AsEnumerable();
But in most cases this is not needed. It makes your query enumerable but does not execute your query. The query will be executed only when iterating.
Btw. .Select(a => a) in your examples is not needed because it happens automatically.
Edit:
Linq-to-entities forbid projecting to mapped types so as I mentioned it comment you must first project to anonymous type, call AsEnumerable and project to the real mapped type.
var query = (from a in Lines
where a.LineId == SomeGuid
select new {
LineId = a.LineId
}).AsEnumerable()
.Select(a => new Line { LineId = a.LineId });
In this case you even don't need anonymous type because you can select a.LineId directly.
If I were to use IEnumerable instead of var in the code example below, will the SQL be generated only during the execution of the foreach statement? Or will it execute as an when the Linq statements are evaluated?
var query = db.Customers.Where (c => c.Age > 18);
query = query.Where (c => c.State == "CO");
var result = query.Select (c => c.Name);
foreach (string name in result) // Only now is the query executed!
Console.WriteLine (name);
Another example:
IEnumerable<Order> query = db.Orders.Where(o => o.Amount > 1000);
int orderCount = query.Count();
Would it be better to use var (or IQueryable) as it would be executed a select count(*)... when .Count() is executed or would it be exactly same with the IEnumerable code shown above?
It would make no difference. var is just syntactic sugar. If you hover over var, you will see what type C# thinks your query is.
From http://msdn.microsoft.com/en-us/library/bb383973.aspx
Beginning in Visual C# 3.0, variables that are declared at method scope can have an implicit type var. An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type. The following two declarations of i are functionally equivalent:
var i = 10; // implicitly typed
int i = 10; //explicitly typed
If you want to perform actions on your query that SQL wouldn't know what to do with, such as a method defined in your class, then you could use AsEnumerable().
For example:
var query = db.Customers
.Where(c => c.Age > 18)
.AsEnumerable()
.Select(c => GetCustomerViewModel());
//put definition of GetCustomerViewModel() somewhere in the same class
Update
As Omar mentioned, if you want your query to be executed immediately (rather than deferred), use ToList(). This will immediately enumerate the IQueryable/IEnumerable and fill the list with the actual data from the database.
In general, the SQL is generated when GetEnumerator is called on the IQueryable.
In your example, there is a subtle difference that you may want to consider. Let's take your original example:
var query = db.Customers.Where (c => c.Age > 18);
query = query.Where (c => c.State == "CO");
var result = query.Select (c => c.Name);
In this case if you change your first query to IEnumerable query = ..., then the second line would use the IEnumerable version of the Where extension (LINQ to Objects) rather than the IQueryable one (LINQ to SQL/EF). As a result, when we start iterating, the first where clause is passed to the database, but the second where clause is performed on the client side (because it has already been converted to an IEnumerable).
Another subtle item you want to be aware of is the following type of code:
var query = db.OrderBy(c => c.State);
query = query.Customers.Where(c => c.Age > 18); // Fails: Widening
In this case, since your original query returns IOrderedQueryable rather than IQueryable. If you try to then assign query to the result of the .Where operation, you're trying to widen the scope of the return type and the compiler will refuse to perform that widening. As a result, you have to explicitly specify the baseline type rather than using var:
IQueryable<Customer> query = db.OrderBy(c => c.State); // Is narrowing rather than widening.
query = query.Customers.Where(c => c.Age > 18);
Linq queries return IQueryable<> or IEnumerable<>, the execution of both is deferred.
As DanM stated, whether or not you use var or IEnumerable<> it all depends on the return value of the method you're calling: if it's an IEnumerable<> or IQuerable<> it'll be deferred, if you use .ToList(), it'll be executed right away.
When to use var comes down to personal choice/style. I generally use var when the return value is understood from the line of code and variable name or if I'm instantiating a generic with a long declartion, e.g. Dictionary<string, Func<Order, object>>.
From your code, it's clear that a collection of Customers/Orders is returned, so I would use the var keyword. Again, this is a matter of personal preference.
I want to add the where clause to a linq statement, but it doesn't behave as i would expected it to.
When i use this code:
IQueryable<Employee> EmpQuery = from e in Session.Query<Employee>() where e.Surname == "Test" select e;
EmpQuery.ToList();
or i use this code:
IQueryable<Employee> EmpQuery = (from e in Session.Query<Employee>() select e).Where(e => e.Surname == "Test");
EmpQuery.ToList();
The where clause is included in the SQL command, but when i try it this way:
IQueryable<Employee> EmpQuery = from e in Session.Query<Employee>() select e;
EmpQuery.Where(e => e.Surname == "Test");
The where clause is not included in the SQL command. Why is this? Is there another way to dynamically add criteria to a Nhibernate Linq query?
You're not using the return value of Where. LINQ is designed around functional concepts - calling Where doesn't modify the existing query, it returns a new query which applies the filter. The existing query remains as it was - which means you can reuse it for (say) a different filter.
Note that your current query expression (from x in y select x, effectively) is pretty pointless. I would suggest simply writing:
var query = Session.Query<Employee>().Where(e => e.Surname == "Test");
Just to clarify on Jon's remark, your implementation would be fine with the following tweak:
IQueryable<Employee> modifiedQuery = EmpQuery.Where(e => e.Surname == "Test");
Then just invoke the appropriate enumerator (ToList, ToArray, foreach) on modifiedQuery. And I wouldn't say that it create a complete new query, but instead creates a query which wraps around the original (kind of along the lines of the adapter pattern). Granted, your example doesn't need the additions, but this is how you would add additional criteria onto an existing LINQ expression, and that is what your question actually asked.
I'm using Enumerable.ToDictionary to create a Dictionary off of a linq call:
return (from term in dataContext.Terms
where term.Name.StartsWith(text)
select term).ToDictionary(t => t.TermID, t => t.Name);
Will that call fetch the entirety of each term, or will it only retrieve the TermID and the Name fields from my data provider? In other words, would I be saving myself database traffic if I instead wrote it like this:
return (from term in dataContext.Terms
where term.Name.StartsWith(text)
select new { term.TermID, term.Name }).ToDictionary(t => t.TermID, t => t.Name);
Enumerable.ToDictionary works on IEnumerable objects. The first part of your statement "(from ... select term") is an IQueryable object. Queryable is going to look at the expression and build the SQL statement. It will then convert that to an IEnumerable to pass to ToDictionary().
In other words, yes, your second version would be more efficient.
The generated SQL will return the entire term, so your second statement will bring down just what you need.
You can set dataContext.Log = Console.Out and look at the different results of the query.
Using my sample LINQPad database, here's an example:
var dc = (TypedDataContext)this;
// 1st approach
var query = Orders.Select(o => o);
dc.GetCommand(query).CommandText.Dump();
query.ToDictionary(o => o.OrderID, o => o.OrderDate).Dump();
// 2nd approach
var query2 = Orders.Select(o => new { o.OrderID, o.OrderDate});
dc.GetCommand(query2).CommandText.Dump();
query2.ToDictionary(o => o.OrderID, o => o.OrderDate).Dump();
The generated SQL is (or just peek at LINQPad's SQL tab):
// 1st approach
SELECT [t0].[OrderID], [t0].[OrderDate], [t0].[ShipCountry]
FROM [Orders] AS [t0]
// 2nd approach
SELECT [t0].[OrderID], [t0].[OrderDate]
FROM [Orders] AS [t0]
No. ToDictionary is an extension method for IEnumerable<T> not IQueryable<T>. It doesn't take an Expression<Func<T, TKey>> but simply a Func<T, TKey> that it'll blindly call for each item. It doesn't care (and doesn't know) about LINQ and the underlying expression trees and stuff like that. It just iterates the sequence and builds up a dictionary. As a consequence, in your first query, all columns are fetched.