Linq to Sharepoint results in invalid cast - linq

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)
{
//...
}

Related

Difference between First, FirstOrDefault and singleOrDefault keywords in ORM

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.

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 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.

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