使用LINQ to XML查询XML中人口超10万的城市仅返回半数结果求助
问题分析与解决方案
看起来你的代码只筛选出了一半符合条件的城市,核心问题在于只检查了每个城市的第一个<population>元素,而忽略了以下几种可能的情况:
- 部分城市存在多个
<population>条目(对应不同年份的人口数据),第一个条目未达标,但后续条目满足人口>10万的条件; - 未处理
<population>元素文本中的前后空白(虽然C#的int.Parse会自动忽略,但养成Trim的习惯更稳妥); - 直接返回XElement对象而非其文本内容,导致输出格式不符合预期。
下面是针对不同需求的修正方案:
方案1:筛选所有存在任意人口数据>10万的城市
如果你只要城市有任意一次人口记录超过10万就纳入结果,可以用这段代码:
var cities = from c in doc.Descendants("city") // 获取当前城市所有有效的人口数据 let validPopulations = c.Elements("population") .Where(p => !string.IsNullOrWhiteSpace(p.Value)) .Select(p => { // 安全转换为整数,避免无效数值报错 if (int.TryParse(p.Value.Trim(), out int population)) return population; return -1; // 标记无效数值 }) .Where(pop => pop > 0) // 过滤无效数值 // 判断是否有至少一个人口数据达标 where validPopulations.Any(pop => pop > 100000) select new { CityName = c.Element("name")?.Value.Trim() ?? "未知城市", MaxPopulation = validPopulations.Max() // 取该城市的最大人口数 }; foreach (var city in cities) { Console.WriteLine($"城市:{city.CityName},最大人口:{city.MaxPopulation}"); }
方案2:筛选最新年份人口>10万的城市
如果你需要基于最新年份的人口数据来筛选,可以调整代码,优先取最新年份的记录:
var cities = from c in doc.Descendants("city") // 获取当前城市所有带年份的有效人口数据,并按年份倒序排序 let latestPopulation = c.Elements("population") .Where(p => !string.IsNullOrWhiteSpace(p.Value) && p.Attribute("year") != null) .Select(p => { if (int.TryParse(p.Value.Trim(), out int pop) && int.TryParse(p.Attribute("year").Value, out int year)) return new { Year = year, Population = pop }; return null; }) .Where(p => p != null) .OrderByDescending(p => p.Year) .FirstOrDefault() // 判断最新人口数据是否达标 where latestPopulation != null && latestPopulation.Population > 100000 select new { CityName = c.Element("name")?.Value.Trim() ?? "未知城市", Year = latestPopulation.Year, Population = latestPopulation.Population }; foreach (var city in cities) { Console.WriteLine($"城市:{city.CityName},{city.Year}年人口:{city.Population}"); }
关键改进点
- 用
Elements("population")替代Element("population"),获取所有人口条目而非仅第一个; - 加入
int.TryParse安全转换,避免因无效数值导致程序崩溃; - 提取元素的
Value并Trim(),去除文本前后空白,让输出更整洁; - 针对多年份数据的场景,增加了灵活的筛选逻辑。
内容的提问来源于stack exchange,提问作者zhuk
相关产品推荐
相关产品推荐

