Monday, 25 November 2013

Don't use SPList.Items, use GetItems() instead

private static void GetItemsFromList()
{
    //from MDSN: It is best practice is to use one of the GetItem* methods of SPList to return a filtered collection of items.

    using (SPSite site = new SPSite(webUrl))
    {
        using (SPWeb web = site.OpenWeb())
        {
            SPList list = web.GetList(ListUrl);  //my list has 2 items
            Console.WriteLine(list.ItemCount);   //returns 2
            Console.WriteLine(list.Items.Count); //returns 0

            foreach (SPListItem item in list.Items)
            {
                // will not go inside loop, because list.Items is empty
            }

            for (int i = 0; i < list.ItemCount; i++)
            {
                var item = list.Items[i];  //will cause ArgumentOutOfRangeException
            }

            var items = list.GetItems(new SPQuery());  //returns all items
        }
    }
}