Click here to Skip to main content
15,850,359 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
string myTown = document.Element("GeocodeResponse").Element("result").Elements("address_component").Where(x => (string)x.Element("type").Value == "locality").Select(x => x.Element("long_name").Value).First();


works fine but

C#
List<GeocoderLocation> geoList = new List<GeocoderLocation>();
                        geoList = (from result in document.Descendants("result")
                                  select new GeocoderLocation
                                  {
                                      Town = result.Elements("address_component").Where(x => (string)x.Element("type").Value == "locality").Select(x => x.Element("long_name").Value).First(),
                                      
                                  }).ToList();

does not. It throws exception InvalidOperationException Sequence contains no elements.

This is attempt to parse geocode from google http://maps.googleapis.com/maps/api/geocode/xml?address=miry%20ln%20uk&sensor=false[^]
Why?
Posted

1 solution

My bad. I assumed that it was throwing exception on first go. But it didn't and the cause of problem was that some nodes didn't contain postcode or something else and therefore being empty.

Solution: instead of .First() use .FirstOrDefault()
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900