Wednesday, September 17, 2014

Querying the SPList Items - best practices

Its time to recollect and replenish my knowledge on basic operation in SharePoint Server Object model coding to write the optimized code.
Especially on querying the List Items in SharePoint List.

Loading the specific list in the memory instead of loading all the list and their meta data available in the SPWeb object in the memory

var list = webObj.GetList(SPContext.Current.Site.Url+"/Lists/ListName/AllItems.aspx");

Loop through all list items through the Items Count property of the SPListItemCollection class.
I feel its good to work with individual item instead of loading all items using RowsLimit in SPQuery class.


 using (SPSite site = new SPSite(SPContext.Current.Site.Url))
                using (SPWeb web = site.OpenWeb())
                    SPList list = web.GetList(web.Url + "/Lists/Friends/AllItems.aspx");
                    SPListItemCollection cols = list.Items;
                    for (int x = 0; x < cols.Count; x++)
                        //Loading the specific items in the memory instead of loading all items.
                        SPListItem item = list.Items[x];