Blog

Implementing Multiple Filters in LINQ Query from Visual Studio

by | Sep 22, 2011 | SharePoint, Software Development, Visual Studio 2010 - C# | 0 comments

A best practice in any application making data calls is to push processing to the server and limit the amount of data that has to come back to the application.

I recently worked on a windows application that uses the Microsoft SharePoint Client Object Model to manipulate lists and their elements. I needed to filter the lists for processing in the application to just the document libraries that were not hidden, contained at least one item, and were not the “Site Assets” or “Style Library.”

Cleary a situation where filtering is desired. I found it easy to find examples for generating a list with one filter. For example:

var web = clientContext.Web;
SP.ListCollection listcoll = web.Lists;

ctx.Load(listcoll,
lists => lists.Include(list => list.Title)
.Where(list => list.BaseTemplate == 101));
ctx.ExecuteQuery();

However, examples on implementing multiple filters such as I needed proved much more challenging. I finally found an example where the implementation used many “.Where” clauses which led to the following attempt.

...
ctx.Load(listcoll,
lists => lists.Include(list => list.Title)
.Where(list => list.BaseTemplate == 101)
.Where(list => list.ItemCount > 0)
.Where(list => list.Title != "Site Assets")
.Where(list => list.Title != "Style Library")
.Where(list => list.Hidden == false));

Unfortunately this would not even compile in Visual Studio 2010.

I decided to try implementing a more common syntax used in ‘if’ statements – using ‘&&’ to combine multiple conditions but within one .Where.

ctx.Load(listcoll,
lists => lists.Include(list => list.Title, list => list.ItemCount)
.Where(list => list.BaseTemplate == 101 &&
list.ItemCount > 0 &&
list.Title != "Site Assets" &&
list.Title != "Style Library" &&
list.Hidden == false));

YES – Success! Finally, listcoll finally had the libraries I needed.

Categories

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *