3

I have a requirement to query SharePoint list items by multiple ids. I have a collection of list item ids and I want to get the list item collection programmatically. Is there anyway to do through C# code?

  • Could you add SharePoint version to your question, please? Also it is unclear whether you are asking about being able to query passing multiple parameters in one go and getting list items matching the query? – Cthulhubutt Sep 14 '16 at 10:03
4

There is a concept of IN Query in Sharepoint where you can use CAMl to hit with multiple conditions . Below is a code snippet where I've used it to create IN query for 1000 ID's.

                SPQuery queryEpisodeDocs = new SPQuery();
                if (count > 500) //count is the number of ID's you have
                {
                    queryEpisodeDocs.Query = @"<Where><Or><In><FieldRef Name='EpisodeID'/><Values>";
                }
                else
                    queryEpisodeDocs.Query = @"<Where><In><FieldRef Name='EpisodeID'/><Values>";


                #region TG in query

                for (int i = 0; i < count; i++)
                {
                    strEpisodeID = episodeItemcollection[i]["ID"].ToString(); //Here you'll get the ID from the array of ID you have
                    if (i % 500 == 0 && i > 0)
                    {
                        //implement it for more than 500 items

                        queryEpisodeDocs.Query += "</Values></In><In><FieldRef Name='EpisodeID'/><Values>";
                        queryEpisodeDocs.Query += "<Value Type='Text'>" + strEpisodeID + @"</Value>";


                    }
                    else
                    {
                        queryEpisodeDocs.Query += "<Value Type='Text'>" + strEpisodeID + @"</Value>";
                    }

                }
                if (episodeItemcollection.Count > 500)
                {
                    queryEpisodeDocs.Query += "</Values></In></Or></Where><OrderBy><FieldRef Name='EpisodeID' Ascending='True' /></OrderBy>";
                }
                else
                    queryEpisodeDocs.Query += "</Values></In></Where><OrderBy><FieldRef Name='EpisodeID' Ascending='True' /></OrderBy>";

                #endregion

You change Fieldref accordingly.

3

You can use CAML as a query language to tell the query which items you want get. Have a look at: https://msdn.microsoft.com/en-us/library/office/ee534956(v=office.14).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2 In the first example you can modify the camlQuery.ViewXml to fit multiple IDs. By doing that you will get a collection of listitems

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.