Is there a way to run this LINQ statement

var items = from SPListItem li in listSettings.Items
    		where li["WebID"].ToString() == SPContext.Current.Web.ID.ToString()
    		orderby li["Title"].ToString()
    		select li;

and simply bind it to my SPGridView, like

gvList.DataSource = items;

and have the SPGridView use the fields in the SPlistItem? My current workaround is to do

select new { ID=li.ID.ToString(), Title=li["Title"].ToString(),Frequency=li["Frequency"].ToString(),Batch=li["Batch"].ToString(),LastDownloaded=li["LastDownloaded"].ToString() }

3 Answers 3

var items = from li in listSettings.Items.OfType<SPListItem>()
                where li["WebID"].ToString() == SPContext.Current.Web.ID.ToString()
                orderby li["Title"].ToString()
                select li;
  • While this works, you should avoid using the SPList.Items collection. What if it contains a huge number of items? Use a CAML query instead, then you can use Linq or whatever to retrieve your data from the returned collection. Feb 15, 2010 at 8:57
  • yes you are totally right, it works but watch out for performances :D
    – GillouX
    Feb 15, 2010 at 10:25

There is no clear way (without 3d-party solutions) to create LINQ query to SharePoint (until 2010th version) without without overhead in perfomance. Use CAML in this case, and yes, sorting, paging and filtering doesn't work with declarative declaration in this case.


I have used similar technique as you describe with binding an anonymous type to the SPGridView and it works fantastic. What I do is to specify a CAML query the traditional to filter the items and then optionally uses the Where query to filter the remaining items. Then as you describe create an anonymous type.

I use this technique in combination with the SharePoint Extensions Library that contains a set of Linq extension methods. This makes the querying and working with complex lists/relations really easy. The key here is to first filter using CAML, especilly with large lists. When you have narrowed down your items you can use Linq to join the results and hook it up to the SPGridView

  • great idea! CAML then LINQ. Awesome Feb 5, 2010 at 17:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.