Accepted answer

You should integrate your foreach into LINQ query:

var query = from item in weatherData.Descendants("Observation")
            group item by (string)item.Element("Station") into g
            let maxDate = g.Max(o => (DateTime)o.Element("DateTime"))
            let latestObservation = g.FirstOrDefault(o => (DateTime)o.Element("DateTime") == maxDate)
            select new Station()
                Name = g.Key,
                MostRecentDate = maxDate,
                LastTemperature = (decimal)latestObservation.Element("Temperature")

But it will give you IEnumerable<Station> not IQueryable<>. You can get IQueryable<Station> by calling AsQueryable() method, but that really doesn't make any sense here.

Also, you can cast XElement to DateTime and Decimal directly, instead of casting to string first and then calling Parse method.

Related Articles