Linq provider for SharePoint does not support Distinct
operator.
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 :
//1 Execute query against SP Linq provider
string keyCol = "SPFieldName";
CamlQuery keyColumnValuesQuery = CamlQuery.CreateAllItemsQuery();
ListItemCollection keyColumnValues = srcDocLib.GetItems(keyColumnValuesQuery);
spContext.Load(keyColumnValues, items => items.Include(item => item[keyCol]), items => items.OrderBy(item => item[keyCol]));
spContext.ExecuteQuery();
//2. Transform LiItemCollection to a List and perform Distinct operation
var uniqueKeyColumnValues = keyColumnValues.ToList().Select(i => i[keyCol]).Distinct();