简体   繁体   中英

Compare Sharepoint List with C#

I am trying to compare two Sharepoint lists. I am using a C# program to add, update, and delete items, based on its ID. If the ID doesnt exist in List1, when the program is ran, I want to delete the IDs from List2. I was wondering how can I delete those items without specifying a specific number in the GetItemById function? Like in this example

using(ClientContext context = new ClientContext(siteUrl)) {
  //Retrieve list items from list 1 here code here

  using(ClientContext target = new ClientContext(siteUrl2)) {
    foreach(ListItem oListItem2 in collListItem2) {
      int exists = 0;
      foreach(ListItem oListItem in collListItem) {
        if (oListItem2["ID"] == oListItem["ID"]) {
          exists++;
        }
      }
      if (exists == 0) {
        ListItem DeleteItem = list2.GetItemById();
        DeleteItem.DeleteObject();
        target.ExecuteQuery();
      }
      return;
    }
  }
}

To delete the items from the second list not in the first, just get all of the items from the first list, and filter the items in the second list based on those ids. Note you can use a hash based lookup to greatly improve performance over a linear search:

var idsFromFirstList = new HashSet<int>(
    collListItem.AsEnumerable()
        .Select(item => item.Id));

var itemsToDelete = collListItem2.AsEnumerable()
    .Where(item => !idsFromFirstList.Contains(item.Id);

foreach(var item in itemsToDelete)
   item.DeleteObject();

target.ExecuteQuery();

Note that you can basically do the exact opposite to find the items to add (create a hashset of the IDs of the items in the target into a set, find all items in the first no tin there, and then add all of those items).

To find items that match you can use a Dictionary<int, ListItem> by putting either set of items into a dictionary, with the ID as the key, and going through the other set, finding the matches. If you are going to do that, you can re-use that dictionary to check for one of the other two conditions as well, to save you one data structure:

var firstSiteItemLookup = collListItem.AsEnumerable()
    .ToDictionary(item => item.Id, item => item);

foreach(var item in collListItem2)
{
    ListItem match;
    if(firstSiteItemLookup.TryGetValue(item.Id, out match))
        UpdateItemToMatch(item, match);
    else
        item.DeleteObject();
}

target.ExecuteQuery();

Can you use the same code to check if an ID in collListItem has been modified then update the same ID in collListItem2? @Servy

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM