0

In the following code, the "FirstOrDefault" function returns a SPlistItem; it is a valid item. However, the "ToList" function throws an exception of "System.NullReferenceException".

Why does FirstOrDefault return a item, that is part of the set I am looking for, but ToList throws an exception?

List<SPListItem> allRecords = get_All_Records();

IEnumerable<SPListItem> results = allRecords.Where(item=>item["key"].ToString() == "4993d76a-9ae4-492b-baab-a9a6e33a3661");

String temp = results.FirstOrDefault()["value"].ToString(); //This line gives one of the items that I am looking for.

List<SPListItem> subSet = results.ToList(); //This line throws exception.

1 Answer 1

2

One of the items in allRecords is null. Because FirstOrDefault only accesses the first item, a valid item is returned. When ToList is called, it accesses all the record and the condition causes an error when it gets to the null record. The following is the solution:

IEnumerable<SPListItem> results = allRecords.Where(item=>
  item !=null && item["key"].ToString() == "4993d76a-9ae4-492b-baab-a9a6e33a3661");
3
  • Hi @amsackett If you solved the problem stated in your original question, you should mark this answer as accepted answer to help future visitors. Thank you for your contribution :) Jun 5, 2017 at 22:25
  • The forum made me wait to accept the answer.
    – amsackett
    Jun 26, 2017 at 13:01
  • yes it's 2 days if it's your answer Jun 26, 2017 at 13:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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