LINQ Lambda Order in writing the query - linq

I have the following query:
var query = db.Prog
.Where (a => a.Prog != "00000" && a.fn != "Koll")
.Select(a => new {a.Prog, a.MEfn})
.OrderByDescending(a => a.MEfn)
The query works fine but wondering if there are general rules on the order in which you write a Lambda linq query. Meaning, .Where comes before .Select, etc.
Can somebody enlighten me on the order in which LINQ needs to be written or best practices.

There isn't a best practice on the order in which you write a LINQ query, it will depend on if you want to do your filtering first, or your projection. For example in your case, you are projecting to an anonymous type which doesn't include the 'fn' property which your filter uses, so it wouldn't be available to use in a where clause if your select was first.
A better practice would be to give your properties less cryptic names. Also, 'fn' doesn't follow the PascalCase for property names, and if it's a field then it probably shouldn't be public.

Yours can be a good order.
Let's distinguish the case where db points to an SQL DB with a very good LINQ provider and the case db is an in-memory object. I guess it's the first.
In case you are using a LINQ to SQL provider, the statements are evaluated only when you materialize the query into an object, so the SQL optimizer (inside the DB) will take care of ordering of statements.
The vice versa occurs when your statements are run against in-memory collections or to materialized collections coming from LINQ to SQL. In that case they are executed sequentially, so you want to execute first those statements that reduce the number of results in the collection. Where is the best candidate!!!

The order that they should be in are completely dependent on the context of what you are doing. So if your OrderBy is simply formatting the data to be friendly to view, put it at the end after you have trimmed your collection, if your looking for the First value of a sorted collection then maybe you would need it before the collection is iterated to get the first.

Related

LINQ- Update, Select and Delete as single query

I have a datatable (say myNameDT) which has data like this
Expected result:
When sector is Price, if it has fund value and component OTHER THAN "Active Return Contribution, It should update the Fundvalue in respective sector of Component Active Return Contribution. same applied for Index Value. Note: After update it should delete the unnecessary rows.
The result should look like,
Need as LINQ only. I have tried something as naive LINQ developer which is not fruitful. Thank you
What you're looking for is not feasible in a single LINQ statement. This is imposed not by LINQ itself but by the concept of SQL that LINQ relies on to perform operations on data. One of the things LINQ does, it lets you chain operations on the same dataset by combining them in a single query, however SELECTs cannot be combined with UPDATEs or DELETEs.
Finally, if what you're looking for is only syntactic sugar - this is not possible. If you are looking for a way to organize a set of data operations in a single TRANSACTION, you may want to look at these questions that give a hint on how LINQ interprets transaction operations:
TransactionScope vs Transaction in LINQ to SQL
How to create a LINQ to SQL Transaction?

How to use linq to entities queries or Lists in linq to sql queries

I have a generic EF repository and need to get items from database using nested where statements.
var categoryGroups = repository.Categories.Where(a => a.Vehicles.Where(v =>
bodyTypesFilter.Any(b => b == v.BodyType)).Count() > 0);
I include only the important part of lambda expression.
Here bodyTypesFilter is a List and I'm getting following exception.
Unable to create a null constant value of type 'System.Collections.Generic.List`1'. Only entity types, enumeration types or primitive types are supported in this context.
I understand that it's due to I'm trying to generate linq to sql query which includes List and it isn't allowed. But I don't know how to avoid it or overcome.
Please help to find out a solution.
It's about the part
bodyTypesFilter.Any(b => b == v.BodyType)
You can't compare objects in EF queries, because the part bodyTypesFilter can't be translated into SQL. Do this in stead:
bodyTypesFilterIds.Contains(v.BodyType.Id)
(or probably v.BodyTypeId)
where bodyTypesFilterIds is a list of Id values in stead of objects.
(Not Any, because that creates a monster query that easily develops into a too deep nesting level).

Linq to ... and Lambda Expressions

I have a big question that has been puzzling me for a long time and that I can't seem to get a straight answer for anywhere and I am sure that if someone can answer this with authority and with good examples that it will help not only me but thousands of developers to come. All I want to know is what are the characteristics of the following concepts and what are the differences between them
Linq
Linq to SQL
Linq to Entities
Linq to Objects
Lambda expressions
Also, in particular, can someone tell us where constructs such as these fall into the above categories
Construct 1
var result = from n in nums
where n < 5
orderby n
select n;
Construct 2
Entities.Person.Where(p => p.FirstName == "John").First();
Your learned clarifications are eagerly awaited.
I'm sure there are some over-simplifications here, but for what it's worth:
Linq is an API designed for dealing with data sets. IQueryable, for instance, comes from the System.Linq namespace. Linq to ... are different implementations that parse the same Linq instructions to perform different operations based on how your data is stored. So Linq to SQL will parse your .Where instruction to produce a sql query with a WHERE clause, while Linq to Objects would take that same instruction and produce a foreach.
A lambda expression is pretty much a shorthand for an anonymous delegate. You identify a lambda by the => operator. Your argument list is at the left hand of the => and the expression that can access those arguments and optionally return a result is at the right hand.
Your two code examples are different syntaxes in which Linq queries can be written. They are called Query syntax and Method syntax, respectively.

This filters in memory right?

I Just want to make sure I understand this correctly...
search is an object that contains a querystring.
Repo.Query returns an ObjectQuery<T>.
From my understanding the chained linq statements will filter the results after entity framework has returned all the rows satisfying the query. So really ALL the rows are being returned and THEN filtered in memory. So we are returning a bunch of data that we don't really want. There's about 10k rows being returned so this is kind of important. Just like to get my confusion cleared up.
var searchQuery = Repo.Query(search)
.Where(entity =>
entity.Prop1.ToUpper().Equals(prop1.ToUpper()) &&
entity.Prop2.ToUpper().Equals(prop2.ToUpper()))
.OrderBy(entity => Repo.SortExpression ?? entity.prop1);
Your Repo.Query(string query) function should return IQueryable<T>.
Then you can filter and order without getting all rows first.
IQueryable(Of T) Interface
hope this helps
If this is to SQL, this will most likely create a SQL query and filter on the server and not in memory.
As a matter of fact, the statement above wouldn't actually do anything.
It's only when you iterate over it that the query will be executed. This is why certain providers (like the EF to SQL one) can collapse expression trees into a SQL query.
Easiest way to check is to use LINQPAD or the SQL Profiler to see what query is actually is executed.

Linq, what is difference in returning data in var, list, IEnumerable and IQueryable?

I am new to Linq please guide me on some basic things.
In read some articles on Linq. Some authers fill data in var from Linq query, some fills list of custom type objects and some fills data in IEnumerable and some do it in IQuryable. I could not get what is difference in these 4 and which one should be used in which situation.
I want to use Linq to SQL. What should I use?
Well, you can never declare that a method returns var - it's only valid for local variables. It basically means "compiler, please infer the static type of this variable based on the expression on the right hand side of the assignment operator".
Usually a LINQ to Objects query will return an IEnumerable<T> if it's returning a sequence of some kind, or just a single instance for things like First().
A LINQ to SQL or EF query will use IQueryable<T> if they want further query options to be able to build on the existing query, with the added bits being analyzed as part of the SQL building process. Alternatively, using IEnumerable<T> means any further processing is carried out client-side.
Rather than focusing on what return type to use, I suggest you read up on the core concepts of LINQ (and the language enhancements themselves, like var) - that way you'll get a better feel for why these options exist, and what their different use cases are.

Resources