Rather than repeatedly query a SharePoint list for information I need, I wanted to create a dictionary from an SPListItemCollection (where the dictionary key is the "Title" value of each SPListItem, and the value is the SPListItem itself). I tried this:

SPListItemCollection documentCodesListItems = documentCodesList.GetItems(query);

Dictionary<string, SPListItem> dictionary = (from SPListItem i in documentCodesListItems select new { Key = i.Title, Value = (SPListItem)i }).ToDictionary(
                a => a.Key,
                a => a.Value);

But I get "Value does not fall within the expected range." exception. Can anybody see my mistake, or should I do this differently?

  • 1
    Your code works fine for me provided I use a unique field other than Title. Dictionary keys should be unique but Title can be the same for many items. Can you try using ID / Internal name? – Akhoy Oct 20 '15 at 17:55
  • Do you have any duplicate Title? – Atish Dipongkor - MVP Oct 20 '15 at 18:02
  • Thanks so much Akhoy and Atish. I figured out that I was (stupidly) forgetting to include the Title field as one of the SPQuery view fields! – K. Jones Oct 20 '15 at 19:50

I was able to reproduce following error when my CAML query is wrong. So it's time to re-check your CAML query again.

Value does not fall within the expected range.

Generating Dictionary from items is perfect. You have to consider following thing while generating Dictionary from items where Title is the Key of Dictionary.

Keys can not be duplicate for Dictionary

Use u2u caml builder for building CAML query

  • Oh thank you so much. It turns out my CAML was not wrong, but I wasn't including the Title as one of the view fields! Doh! I hadn't looked at other things before because I was so sure it was how I wrote the Linq. Thanks again! – K. Jones Oct 20 '15 at 19:49

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.