使用LINQ和EF Core查询时的重复输出与计数错误问题排查
问题修复:重复输出统计语句与客户数量计算错误
问题原因分析
- 重复输出统计语句:第一个
query返回的是匹配城市的每一条客户记录的City字段,foreach会遍历所有符合条件的记录,因此重复输出统计语句。 - 客户数量计算错误:
item.City.Count()是计算City字符串的字符长度(比如"London"共6个字符),并非符合条件的客户总数,属于逻辑误用。
修复方案
方案1:一次性加载数据(推荐,减少数据库查询)
将符合条件的客户一次性查询出来,既可以统计总数,又能遍历输出公司名称,避免多次访问数据库:
static void ReturnCities() { WriteLine("Enter the name of a city: "); string? city = ReadLine(); using (var db = new Northwind()) { // 一次性获取目标城市的所有客户数据 var cityCustomers = db.Customers .Where(customer => customer.City == city) .ToList(); // 仅输出一次统计信息 WriteLine("There are {0} customers in {1}: ", arg0: cityCustomers.Count, arg1: city); // 遍历输出所有公司名称 foreach (var customer in cityCustomers) { WriteLine($" {customer.CompanyName}"); } } }
方案2:分开统计与查询(适合大数据量场景)
如果目标城市客户数据量极大,不想一次性加载所有数据,可以分开统计总数和查询公司名称:
static void ReturnCities() { WriteLine("Enter the name of a city: "); string? city = ReadLine(); using (var db = new Northwind()) { // 单独统计目标城市的客户总数 int customerCount = db.Customers .Count(customer => customer.City == city); // 仅输出一次统计信息 WriteLine("There are {0} customers in {1}: ", arg0: customerCount, arg1: city); // 查询并遍历输出公司名称 var companyNames = db.Customers .Where(customer => customer.City == city) .Select(customer => customer.CompanyName); foreach (var name in companyNames) { WriteLine($" {name}"); } } }
修复效果
运行修复后的代码,输入"London"会得到正确输出:
Enter the name of a city: London There are 6 customers in London: Around the Horn B's Beverages Consolidated Holdings Eastern Connection North/South Seven Seas Imports
内容的提问来源于stack exchange,提问作者TheStudentMans
相关产品推荐
相关产品推荐

