批量删除SharePoint 2010的List中的item

第一种方式:循环遍历List中的所有item,然后根据条件去判断当前item是否应该被删除【注:要用 i-- 方式去遍历,这也是删除集合里面item的常用做法,如果用 i++ 的方式去遍历删除,会出错,原因显而易见!】

SPList targetList = null;
            try
            {
                targetList = currentWeb.GetList(currentWeb.ServerRelativeUrl.TrimEnd('/') + listUrl);
            }
            catch { }
            if (targetList != null)
            {
                for (int i = targetList.ItemCount - 1; i >= 0; i--)
                {
                    targetList.Items[i].Delete();
                }
            }

 

第二种方式:用批量删除的方式处理,这种方式要比第一种方式效率更高(推荐使用)

代码如下所示: 

SPList targetList = null;
            try
            {
                targetList = currentWeb.GetList(currentWeb.ServerRelativeUrl.TrimEnd('/') + listUrl);
            }
            catch { }
            if (targetList != null)
            {
                StringBuilder sbDelete = new StringBuilder();
                sbDelete.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Batch>");
                foreach (SPItem item in targetList.Items)
                {
                    if (item["Title"] != null)
                    {
                        sbDelete.Append("<Method>");
                        sbDelete.Append("<SetList Scope=\"Request\">" + targetList.ID + "</SetList>");
                        sbDelete.Append("<SetVar Name=\"ID\">" + Convert.ToString(item.ID) + "</SetVar>");
                        sbDelete.Append("<SetVar Name=\"Cmd\">Delete</SetVar>");
                        sbDelete.Append("</Method>");
                    }
                }
                sbDelete.Append("</Batch>");
                try
                {
                    currentWeb.ProcessBatchData(sbDelete.ToString());
                    targetList.Update();
                }
                catch (Exception ex)
                { }
            }

 

更多资讯:

 http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spweb.processbatchdata.aspx 

 http://sharepoint.stackexchange.com/questions/26542/deleting-all-the-items-from-a-large-list-in-sharepoint

...........

posted @ 2013-09-06 16:31  Eric Sun  阅读(1535)  评论(0编辑  收藏  举报