Вопрос

What is the best practice way to get all items from SPList(with query or without)

This is my ways :

  static void Main(string[] args)
    {
        try
        {
            using (SPSite mySite = new SPSite("http://sf-spsdev04/sites/gkk92"))
            {
                using (SPWeb myWeb = mySite.OpenWeb())
                {
                    SPList myList = myWeb.Lists["Employees"];

                    SPListItemCollection myItems = myList.GetItems();


                    //1st way
                    foreach (SPListItem item in myItems)
                    {
                        Console.WriteLine(item["Title"]);
                    }

                    //2nd way
                    foreach (SPListItem item in myList.GetItems())
                    {
                        Console.WriteLine(item["Title"]);
                    }

                    //3th way
                    foreach (SPListItem item in myWeb.Lists["Employees"].Items)
                    {
                        Console.WriteLine(item["Title"]);
                    }
                }
            }
        }
        catch(Exception ex)
        {
            throw new Exception(ex.ToString());
        }

What are yours ?

Это было полезно?

Решение

Using SPList.Items property is bad practice. Each time the property is accessed, it requests all items with all fields from database. Instead you should always use SPList.GetItems().

  • SPList.GetItems(params string[]) - you can use it to load only the fields that you need. As far as I remember it'll only return items in the root folder of the list.
  • SPList.GetItems(SPQuery) - you'll need to create the query yourself. You should specify view fields and set scope to RecursiveAll if you want to get items from subfolders. You can completely skip the <Query> tag if you want all items.

I know it requires far more code tha using Items, but this is the right way to do it.

Другие советы

If it is just a case to get all items than I always use DataTable to get allitems using below code & do the operations.

static void Main(string[] args)
{
    try
    {
        SPWeb oWebsite = SPContext.Current.Web;
        SPList oList = oWebsite.Lists["Employees"];
        SPListItemCollection collListItems = oList.GetItems();

        DataTable dt = collListItems.GetDataTable();

        oWebsite.Dispose()
    }
    catch(Exception ex)
    {
        throw new Exception(ex.ToString());
    }
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с sharepoint.stackexchange
scroll top