I often see linq queries written in either of these forms:
Form #1:
from t1 in table1
where t1.SomeField == "Something"
select t1.FieldName
Form #2:
table1.Where(c=> c.SomeField == "Something").Select(n=> new {n.FieldName})
What is the difference between these two forms of Linq queries?
Is there any difference in performance ?
Also when I search for Linq query tutorials I always get results for
the first form, if I want to learn the syntax for the second Linq
form below, what keyword to use for the search?
The second one is with the short lambda expression
No, the second one however is faster to write.
Use lamba expression to find it.
The first version is a bit easyer to read according to many.
However lambda is faster to write, and personally I think it's just as clear as the first one.
Good luck!
The first one is called query expression and second one is called lambda expression, They are equivalent. Two syntax will compile to exactly the same code. The compiler changes the query expression into the equivalent Lambda expression before compiling it, so the generated IL is exactly the same.
One more thing:
Chained lambdas are much more readable.
The first form uses query syntax and the second form is called lambda expressions. There is no difference in performance, nevertheless the second form relies on generic delegates which gives you more flexibility to plug-in the expression from external layers, or pass them as method parameters.
refer to : https://msdn.microsoft.com/en-us/library/bb397687.aspx
for more info.
Search for LINQ lambda expressions.
Form # 2 is the actual c# form.
Form # 1 just adds a syntatic sugar and query format for Form # 2.
I prefer Form # 2 as it is aligned well with c# code.
Related
What is difference between these 2 queries in EF, which is best and why?
using (var context = new BloggingContext())
{
var blogs = (from b in context.Blogs select b).ToList();
var blogs = context.Blogs.ToList();
}
I believe your question is about Method Syntax vs Query Syntax. Your first query is based on Query Syntax and the second one is based on Method syntax.
See: Query Syntax and Method Syntax in LINQ (C#)
Most queries in the introductory Language Integrated Query (LINQ)
documentation are written by using the LINQ declarative query syntax.
However, the query syntax must be translated into method calls for the
.NET common language runtime (CLR) when the code is compiled.
EDIT:
With your edited code snippets, there is no difference between two queries at the time of execution. Your first query is based on query syntax which will compile into method syntax (your second query). To select between those two is a matter of choice. I personally finds method syntax more readable.
Old Answer:
However,There is a major difference between your two queries. Your first query is just a query construct, It hasn't been executed,considering that you have tagged Entity framework, Your first query will not bring any records from database in memory. To iterate the result set you need ToList(), ToArray() etc.
Your second query is infact getting all the records from your table and loading in a List<T> object in memory.
Also see: Deferred query execution
In a query that returns a sequence of values, the query variable
itself never holds the query results and only stores the query
commands. Execution of the query is deferred until the query variable
is iterated over in a foreach or For Each loop. This is known as
deferred execution; that is, query execution occurs some time after
the query is constructed. This means that you can execute a query as
frequently as you want to. This is useful when, for example, you have
a database that is being updated by other applications. In your
application, you can create a query to retrieve the latest information
and repeatedly execute the query, returning the updated information
every time.
Totally Agreed with #Habib right answer courtesy #Habib
Remember I copied from #Habib
I believe your question is about Method Syntax vs Query Syntax. Your first query is based on Query Syntax and the second one is based on Method syntax.
See: Query Syntax and Method Syntax in LINQ (C#)
Most queries in the introductory Language Integrated Query (LINQ) documentation are written by using the LINQ declarative query syntax. However, the query syntax must be translated into method calls for the .NET common language runtime (CLR) when the code is compiled.
EDIT: With your edited code snippets, there is no difference between two queries at the time of execution. Your first query is based on query syntax which will compile into method syntax (your second query). To select between those two is a matter of choice. I personally finds method syntax more readable.
First query doesn't perform anything, you are just constructing the query.
Second query fetches all the blog records from DB and load them into memory.
Which is best is depends on your needs.
Edit: If you are asking for syntax, there is no difference.The query syntax will be compiled into extension method calls by the compiler.
Apart from that, this:
from b in context.Blogs select b
is kinda pointless. It's equivelant to context.Blogs.Select(x => x). So in this case I would go with context.Blogs.ToList();
http://geekswithblogs.net/Martinez/archive/2009/06/29/understanding-expression-trees.aspx
By reading this article that expline what are Expression trees and what they are used for I have some question thats the article those not answer me clearly.
A. What is the difference between Data Structure and 'compiled piece of code'.
* I know that data structure is Array,List,.. But this is not the answer I am looking for.
B. Why is it better to use data structure in Entity Framework than 'compiled piece of code' in terms of efficiency.
Answer to both A and B.
The compiled piece of code can not be reverse engineered into something that you can translate to SQL. There are to many details that made the original concepts you want to translate to SQL go away. The expression trees can be analyzed and understood at run time, when the compiled code can not.
Another meta representation of the queries would be possible to use, but the expression trees gives the advantage that existing plumbing in the compiler can be used for a lot of the heavy work.
An Expression is code representing code. It is not an executable piece of code that you can run until you call Compile().
An Expression contains an object graph that describes some code. So the example function:
x => x + 1
Is representing a function that takes 1 parameter, and returns the expression (x + 1). As an object graph, it's something like this:
Expression
AdditionExpression
RightValue
VariableExpression (x)
LeftValue
LiteralExpression (1)
You could parse through the expression and figure out the name of the parts of the expression, or what the literal value is, or what the operation is. Once it is compiled, it is a logical sequence of operations, and all of that metadata is lost.
In terms of Entity Framework, given a sample expression like so:
myObjects.Where(x => x.Id > 10).ToList()
The LINQ to SQL IQueryable provider is inspecting this expression, finding the name of the property Id and then finding the literal value of 10 to convert that into a SQL statement. If this was a function (a compiled unit of code), there is no metadata to inspect, and conversion to SQL would be impossible. It also allows you to deconstruct things into supported and unsupported expressions for efficiency in making sure your SQL query returns the requested data only, instead of a large data set.
I was able to create a LINQ statement that I thought was strange and wanted to see if anyone else had experience with it.
I've simplified it to this:
var x = db.Test
.Where(a => a.Field1 == Utils.CreateHash(Preferences.getValue(a.Field2)))
.FirstOrDefault();
Now how does this translate to database code? Wouldn't LINQ need to do a double query for every single row, i.e. for row a:
1) Query a.Field2
2) Return value to run Utils.CreateHash(Preferences.getValue(a.Field2))
3) Take that value from step 2 and compare it against a.Field1
4) Repeat 1-3 until I've gone through all the rows or returned a matching row
Wouldn't this be extremely inefficient? Or is LINQ smart enough to run this in a better way? Note, I haven't actually run this code so another possibility is a runtime error. Why wouldn't LINQ be smart enough to detect a conflict then and not let me compile it?
The query as is will not work since have a call to Utils.CreateHash in your lambda that you are trying to execute on the DB - in that context you cannot execute that method since there simply is no equivalent on the DB side hence the query will fail.
In general the ability of 3rd party Linq IQuerable providers (e.g. Linq to SQL, Linq to Entities) to access in memory constructs such as methods or classes is very limited, as a rule of thumb at most accessing primitive values or collections of primitives will work.
Just to add fast...
A good example to know how this works would be to write (extreme case I agree, but best :) or go through the source code for a custom (open source) LINQ provider (e.g. http://relinq.codeplex.com/ has one etc.).
Basically (I'm simplifying things here a bit), a LINQ provider can only 'map' to Db (supported SQL, functions) what he 'knows' about.
i.e. it has a standard set it can work with, other than that, and with your custom methods (that do not translate to constants etc.) in the frame, there is no way to resolve that on the 'Db/SQL side'.
E.g. with your 'custom' linq provider (not the case here) you could add a specific extension call e.g. .MyCalc() - which would be properly resolved and translated into SQL equivalent - and then you'd be able to use it.
Other than that, I think if I recall correct, provider will leave that as an expression, to resolve when it returns from the Db 'fetch', query operation. Or complain about it in certain cases.
Linq is based on IQueryable - and you can take a look at extension methods provided there for SQL equivalents supported.
hope this helps
EDIT: whether things 'work' or not doesn't matter - it still doesn't mean it'd execute on the Db context - i.e. it'd be unacceptable performance wise in most cases. IQueryable works with expressions (and if you look at the interface) - and linq is executed when you invoke or enumerate usually. At that point some of the expressions may evaluate to a const value that can be worked into a SQL, but not in your case.
Best way to test is to test back the SQL generated by query (possibly this one I think Translate LINQ to sql statement).
No.
The LINQ provider will run a single SELECT query that selects both fields, then execute your lambda expression with the two values for each returned row.
I have a
class A {
public int X;
public double Y;
public string Z;
// and more fields/properties ...
};
and a List<A> data and can build a linq query like e.g.
var q = from a in data where a.X > 20 select new {a.Y, a.Z};
Then dataGridView1.DataSource = q.ToList(); displays the selection in my DataGridView.
Now the question, is it possible to build the query from a text the user has entered at runtime? Like
var q = QueryFromText("from a in data where a.X > 20 select new {a.Y, a.Z}");
The point being, that the user (having programming skills) can dynamically and freely select the displayed data.
Dynamic Linq baby!
r.e. comment.
Yes, the example as written may not be possible using Dynamic Linq, but if you factor out the constants, e.g. 'from a in data' you are left with a 'where' and a 'select' which can be expressed with dynamic linq.
so two text boxes, maybe three if you include an orderby, could possibly satisfy your requirements.
Just a thought.
Jon has an interesting approach but i would be leery of compiling and executing unrestrained code.
Well, you can use CSharpCodeProvider to compile code at execution time. Have a look at Snippy for an example of this. In this case you'd need to compile the user code in a method which accepts a List<A> called data. My experience is that it works, but it can be slightly fiddly to get right - particularly in terms of adding the appropriate references etc.
Answering it pretty late; though, it will help someone who visits this page.
I had similar requirement and I solved it by dynamically compiling string as LINQ query, executing it over in-memory collection and collecting the result. Only catch is user input needs to be valid C# compile-able code else it returns an exception message instead of result.
Code is pretty long so here is the github link
Sample application on github shows multiple examples including projection.
Although there may be some ways to do this, LINQ simply isn't designed for this scenario. Using CodeDOM (as Jon suggested) is probably the only way to get that easily done. If you trust the user and he/she has programming skills, you could perhaps just use old fashioned methods and let the user enter the query using SQL?
If you, on the other hand, choose to create some visual tool for constructing queries, you don't need to build them by composing strings and you can compose expression trees instead. For example using Linq Kit and AsExpandable.
check out this library
http://msdn.microsoft.com/en-us/vcsharp/bb894665.aspx
I am trying to convert this test code to C# and having a problem with the Trim command. Has anyone done anything similiar like this in C# going to use this with a text box for searching the aspx page.
Dim q = From b In db.Blogs _
Where b.BlogContents.Contains(txtSearch.Text.Trim()) Or _
b.BlogTitle.Contains(txtSearch.Text.Trim()) _
Select b
What is the issue you are having? And what LINQ provider is this? An in-memory set (LINQ-to-Objects)? Or LINQ-to-SQL? Or LINQ-to-Entities?
I suspect you are getting something about the db LINQ provider not knowing about Trim() - in which case, try doing the trim first:
string s = txtSearch.Text.Trim();
var q = from b in db.Blogs
where b.BlogContents.Contains(s) || b.BlogTitle.Contains(s)
select b;
This addresses two three separate issues:
1: captures: in the original, it is txtSearch that is captured into the query, which has complications; by evaluating the Trim first, it is s that is captured, which is a simple immutable string
2: expression complexity: with expression-based LINQ (i.e. to a database), the entire expression (including .Text, .Trim, etc) is part of the expression. If the LINQ provider doesn't recognise one or more of those, it will fail. By reducing it to a string first, all the LINQ provider needs to handle is a string, which every provider should be fine with.
(added)
3: repeated computation: LINQ-to-Objects is very literal; if you ask it to use a complex operation in a Where (etc), it will, even if it is obvious that the answer is unchanged per row; i.e. txtSearch.Text.Trim() shouldn't change per row, so why evaluate it per row? Evaluate it before the query and it is only done once.
not sure what you are asking but the Trim function in c# is the same.
http://msdn.microsoft.com/en-us/library/t97s7bs3.aspx
I've come across this too when switching to C#. The intellisense is way worse in C# : <
Make sure you aren't leaving out the () after Trim.