The best way to retrieve results from sharepoint list in terms of performance using client object model is to use ‘include’ with lambda expression.
using (var context = newClientContext(http://server/site/sitecollection))
{
List currentList = context.Site.RootWeb.Lists.GetByTitle(“MyList”);
CamlQuery camlQuery = newCamlQuery();
camlQuery.ViewXml =“[YourViewXmlhere]”;
ListItemCollection collListItem = currentList.GetItems(camlQuery);
context.Load(collListItem, items => items.Include(item => item[“ID”], item => item[“SomeField1”], item => item[“SomeField2”]));
context.ExecuteQuery();
foreach (ListItem item in collListItem)
{
//Play with the listitem here
}
}
What if I had to generate the lambda expression for the include method at runtime. Every expression I created gave me an error saying ‘the query expression is not supported’. Actually, ClientContext.Load() method doesn’t support lambda expressions created at runtime. Due to this limitation, you’ll get ‘InvalidQueryExpressionException’ . Alternative is to use, ClientContext.LoadQuery().
Code snippet –
using(var context = newClientContext(http://server/site/sitecollection))
{
List currentList = context.Site.RootWeb.Lists.GetByTitle(“MyList”);
CamlQuery camlQuery = newCamlQuery();
camlQuery.ViewXml =“YourViewXmlhere”;
ListItemCollection collListItem = currentList.GetItems(camlQuery);
List<string> viewFields = newList<string>();
viewFields.Add(“ID”);
viewFields.Add(“SomeField1”);
viewFields.Add(“SomeField2”);
Expression<Func<ListItem, object>>[] listItemExpressions = CreateListItemLoadExpressions(viewFields);
IEnumerable<ListItem> resultData = context.LoadQuery(collListItem.Include(listItemExpressions));
context.ExecuteQuery();
foreach (ListItem item in resultData)
{
//Play with the listitem here
}
}
private static Expression<Func<ListItem, object>>[] CreateListItemLoadExpressions(List<string> viewFields)
{
List<Expression<Func<ListItem, object>>> expressions = new List<Expression<Func<ListItem, object>>>();
foreach (string viewFieldEntry in viewFields)
{
string fieldInternalName = viewFieldEntry;
Expression<Func<ListItem, object>> retrieveFieldDataExpression = listItem => listItem[fieldInternalName];
expressions.Add(retrieveFieldDataExpression);
}
return expressions.ToArray();
}
Thanks Manvir, this was a lifesaver as no one reponded on stackoverflow.
http://stackoverflow.com/questions/16634724/sharepoint-linq-query-to-retrieve-specific-columns-from-a-list
Thanks it’s helps alot.