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.
Related
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?
eI need to select a particular single data element from first row ordered descending by date. Please specify the differences between the following keywords.
First
FirstOrDefault
singleOrDefault
Also need the precedence/order and usage rules of placing Orderby, where & select in Linq ORM Query. It would be much helpful if answer could be clear & descriptive.
Thanks in advance
A quick Google gives you the following Questions which address your question:
When to use .First and when to use .FirstOrDefault with LINQ?
LINQ: When to use SingleOrDefault vs. FirstOrDefault() with filtering criteria
You might also find the following article useful as it goes into each method:
http://www.technicaloverload.com/linq-single-vs-singleordefault-vs-first-vs-firstordefault/
As stated in the answers, the names do give it away (to those familiar), but here's a quick overview:
First
Will return the first entry in a collection (one or more results returned), will throw an exception if no records returned.
FirstOrDefault
Will return the first entry in a collection (one or more results returned), will return the appropriate default object if no records returned
SingleOrDefault
This one isn't really the same as the previously mentioned functions, it will return the result only if only one record is returned, otherwise will return the appropriate default object.
I tend to use First if I know that my results will always return "something", I use FirstOrDefault when I just want the first element but know that sometimes the query might return nothing. I've yet to personally use SingleOrDefault but it should only be used where your query is only ever going to return one row and that returned results should be ignored if more than one result exists.
I am programming a Silverlight application in c#, which takes lists from a sharepoint.
I want the distinct elements from a specific column in the list.
After getting the query I can't handle with the var-datatype. The program exists everytime, when I want to make a datacast, for example in an ListItemCollection.
Here is the code:
ListItemCollection bla;
var result = bla.Select(m => m["Region"]).Distinct();
ListItemCollection a = (ListItemCollection)result; //Error happens here
LINQ deals with instances of IEnumerable<> or IQueryable<>. Distinct returns an IEnumerable<> or IQueryable<> depending on the type of the original collection. In your case, it returns an IQueryable
You are trying to cast that IQueryable to a ListItemCollection, which understandably results in an invalid cast exception.
You don't need to do something else to start working with the items. You can iterate over them with foreach, convert them to an array or list with ToArray() and ToList() etc
Linq provider for SharePoint does not support Distinct operator which is why this error occurs.
According to MSDN:
Some LINQ queries cannot be completely translated into CAML. However,
however such queries can, in principle, run correctly because they can
be executed in two stages. First, the LINQ to SharePoint provider
translates as much of the query into CAML as it can and executes that
query
Please refer Unsupported LINQ Queries and Two-stage Queries for a more details.
Two stage approach
To correct this error, you should cut your queries in two stages to force the first query execution before the second one. To do that, you should for example transform the first IEnumerable<T> in a list thanks to ToList() method.
The following example demonstrates how to return unique values from ListItemCollection object:
var result = items.ToList().Select(i => i["Region"].ToString()).Distinct(); //System.Linq.Enumerable.DistinctIterator<string> type
foreach (var item in result)
{
//...
}
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.
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.