Reputation: 48045
This is my code:
var coordinateTratte = doc.Descendants(ns + "Folder").First().Descendants(ns + "Folder")
.Descendants(ns + "Placemark").Select(n =>
{
string[] coordinates = n.Descendants(ns + "coordinates").First().Value.Split(' ');
foreach (var coordinate in coordinates)
{
var coordinateLatLng = coordinate.Split(',');
return new
{
latitude = coordinateLatLng.Last(),
longitude = coordinateLatLng.First()
};
}
});
and it says near n =>
that some values could not be expressed as Lambda expression.
Where am I wrong?
Upvotes: 2
Views: 127
Reputation: 727097
The problem is that your lambda expression tries to return items "piecemeal" using a loop, while Select
expects it to return the whole thing at once.
You can fix your code in several ways - for example, you could convert your foreach
loop to a Select
, and use SelectMany
, like this:
var coordinateTratte = doc.Descendants(ns + "Folder").First().Descendants(ns + "Folder")
.Descendants(ns + "Placemark").SelectMany(n =>
{ // ^^^^
string[] coordinates = n.Descendants(ns + "coordinates").First().Value.Split(' ');
return coordinates
.Select(coordinate => coordinate.Split(','))
.Select(coordinateLatLng => new
{
latitude = coordinateLatLng.Last(),
longitude = coordinateLatLng.First()
});
});
I want to return an object such as
Dictionary<string,List<object>>
where object is latitude and longitude
You can change the code like this:
var coordinateTratteDict = doc.Descendants(ns + "Folder").First().Descendants(ns + "Folder")
.Descendants(ns + "Placemark").Select((n,i) =>
{
string[] coordinates = n.Descendants(ns + "coordinates").First().Value.Split(' ');
return new {
Index = i
, CoordList = coordinates
.Select(coordinate => coordinate.Split(','))
.Select(coordinateLatLng => new
{
latitude = coordinateLatLng.Last(),
longitude = coordinateLatLng.First()
})
.ToList()
};
})
.ToDictionary(p => "Block_"+p.Index, p => p.CoordList);
Upvotes: 8