Linq Query instead of Contains Operator for Performance issue - linq

I have to Pull all customers whose ids are in the list
I have a list of CustomerID`s
List custidlist=new List{1,2,3....etc.}();
i have to write a linq query to get all customers whose id`s are in the above list
custidlist.
var customers=db.Customers.Where(c=> custidlist.Contains(c.customerid));
Using Contains is not good in performance issue.
Can we use COMPARE OPERATOR LIKE THIS
var customers=db.Customers.Where(c=> custidlist.Compare(c.customerid)); ????
I Heard Compare is best for Performance

Since this is Linq to SQL / Entities your Linq Contains query will be translated to a SQL statement roughly like:
select * from Customers where customerId in (1,2,3)
Not only is your other suggestion not supported, but also you cannot do any better than this SQL performance wise.

When you write a Contains query in Linq to SQL it iwll be fired as an in query in SQL and running your query on the databse should be the fastest..
one caveats to this though is to remember in query might have a limit on the number of entities I think its around 2000+ in sql server and the way around this would be to batch your query.

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?

LINQ Lambda Order in writing the query

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.

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.

Dynamic linq: passing entire query as string

Looking at Dynamic Linq, it's possible to use strings to define the key parts of the query. My question is, is it possible to pass the entire query in as a string?
ie: var foo = "from..."
LINQ stands for "Language INtegrated Queries" - it's compiled with the rest of the code, not parsed on the run. You can use Microsoft.CSharp.CSharpCodeProvider to compile your query on the run - but you will have to know in advance what local objects you want to send to the query.
That's not possible in dynamic LINQ -- dynamic LINQ only replaces specific pieces of the query. You can use ExecuteQuery on the data context in LINQ to SQL or SqlQuery on a DbSet<T>, though, to execute specific SQL commands.

LINQ query to SQL Script

Is anyone heard of any tool writing LINQ queries and converting them to SQL queries?
I mostly need this because I am a .NET developer and I'm weak in this section of SQL queries where sometimes I need them.
Thank you.
Have you tried using LINQPad? That lets you see the SQL generated when it runs the query - and of course it's easy to experiment with to get the LINQ query right to start with :)
If you write your query against a linq-to-sql datacontext, you can get the query text out like this:
CustomDataContext dc = new CustomDataContext(); //your DataContext here.
IQueryable<Customer> customerQuery = GetQuery(dc); //your query constructed here.
Console.WriteLine(dc.GetCommand(customerQuery).CommandText);
Use sql profiler to get the sql as it is executed against the sql database.

Resources