LINQ: get 'Use the new keyword to create an object instance' when more than one records are returned
...new to LINQ and could do with some help.
I'm querying some remote xml and using LINQ to put the results into a List. When the xml query only returns 1 record all is fine and i get a fully populated 'GetMPResult' object by accessing [0] item in the list.
...but, if there is more than 1 record returned in the xml, i get 'Use the new keyword to create an object instance'
any ideas?
XDocument myData = XDocument.Parse(e.Result);
List<GetMPResult> mp = (from mpItem in myData.Descendants("twfy")
select new GetMPResult
{
Member_id = mpItem.Element("member_id").Value,
House = mpItem.Element("house").Value,
First_name = mpItem.Element("first_name").Value,
Last_name = mpItem.Element("last_name").Value,
Constituency = mpItem.Element("constituency").Value,
Party = mpItem.Element("party").Value,
Entered_house = mpItem.Element("entered_house").Value,
Entered_reason = mpItem.Element("entered_reason").Value,
Left_house = mpItem.Element("left_house").Value,
Left_reason = mpItem.Element("left_reason").Value,
Person_id = mpItem.Element("person_id").Value,
Title = mpItem.Element("title").Value,
Lastupdate = mpItem.Element("lastupdate").Value,
Full_n开发者_StackOverflow社区ame = mpItem.Element("full_name").Value,
Url = mpItem.Element("url").Value,
Image = mpItem.Element("image").Value,
Image_height = mpItem.Element("image_height").Value,
Image_width = mpItem.Element("image_width").Value,
}).ToList<GetMPResult>();
GetMPCompleteEvent(mp[0]);
This doesn't look like it has to do with the number of objects, since it's the error message from NullReferenceException
.
I think that there's simply some element among those you are processing that does not exist even though you are expecting it, so you get the null reference.
Try commenting out all the property setters in the initialization list (select new GetMPResult
) -- if it doesn't throw, it means you found the problem.
精彩评论