How to iterate over a ShimListItemCollection (Shim of Microsoft.SharePoint.Client.ListItemCollection) with C#?

Puneeth, C 81 Reputation points
2022-01-28T05:29:54.743+00:00

I am trying to write a unit test method for the following code:

public static void MoveItems(ShimListItemCollection listItems){
foreach (ListItem item in listItems)
{
// Do Something
}
}

When call ACT in Arrage, Act and Assert methodology, I am passing in a Shim of that ListItemCollection as creating one just to test the function seems not feasible.

// Act
Program.MoveItems(new ShimListItemCollection());

However, this throws an error of null pointer exception and fails to iterate over the ShimListItemCollection as one would expect.

How do I get around this?

Thanks in advance.

Microsoft 365 and Office | SharePoint | Development
Microsoft 365 and Office | SharePoint | For business | Windows
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. RaytheonXie_MSFT 40,481 Reputation points Microsoft External Staff
    2022-01-28T08:05:49.613+00:00

    Hi @Puneeth, C ,
    You can refer to the following code to iterate over a sharepoint ListItemCollection

    using (ClientContext clientContext = new ClientContext("http://MyServer/sites/MySiteCollection"))  
    {  
    List targetList = clientContext.Web.Lists.GetByTitle("List Name");  
       
    CamlQuery oQuery = CamlQuery.CreateAllItemsQuery();  
       
    ListItemCollection oCollection = targetList.GetItems(oQuery);  
    clientContext.Load(oCollection);  
    clientContext.ExecuteQuery();  
       
    foreach (ListItem oItem in oCollection)  
    {  
    Console.WriteLine(oItem["Title"].ToString());  
    }  
    }  
    

    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.



Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.