LinQ C#中用Group By与多Where子句统计指定国家年度仪式数
问题描述
数据源包含三列:CYear(日期类型)、Country(涵盖100个国家)、Ceremony。需对比巴基斯坦和印度在2010-2013年的仪式数据,获取两国每年的仪式总数。已编写部分LinQ查询,需完善并实现表格形式展示。
原始LinQ代码片段:
var que = (from e in dataset where (e.country == "Pakistan" || e.Country == "India" ||e.CYear == 2010 || e.CYear == 2011 || e.Start.Year == 2012) select e.Ceremony // Group by for a total number of ceremonies each year // in the specific countries // to show to the user for better understanding
解决方案
1. 完善LinQ查询
首先修正where条件的逻辑错误——原条件用||导致筛选范围混乱,需同时满足「国家为巴基斯坦/印度」且「年份在2010-2013区间」。之后通过GroupBy按年份+国家组合分组,统计每组的仪式总数。
完整查询代码
var ceremonyStats = from e in dataset where (e.Country == "Pakistan" || e.Country == "India") && e.CYear.Year >= 2010 && e.CYear.Year <= 2013 group e by new { Year = e.CYear.Year, e.Country } into grouped select new { grouped.Key.Year, grouped.Key.Country, TotalCeremonies = grouped.Count() };
代码说明
- 修正筛选逻辑:用
&&关联国家和年份条件,确保只获取目标两国、2010-2013年的数据 - 组合分组键:按
年份+国家分组,避免同一国家不同年份的数据混淆 - 统计总数:用
grouped.Count()计算每组的仪式数量,返回包含年份、国家、总数的结构化数据
2. 表格形式展示数据
根据不同运行环境,提供两种常见的表格展示方式:
方式一:WinForms DataGridView绑定
// 将查询结果转为List并绑定到DataGridView var statsList = ceremonyStats.ToList(); dataGridView1.DataSource = statsList; // 优化列头显示 dataGridView1.Columns["Year"].HeaderText = "年份"; dataGridView1.Columns["Country"].HeaderText = "国家"; dataGridView1.Columns["TotalCeremonies"].HeaderText = "仪式总数";
方式二:控制台输出表格
// 打印表头 Console.WriteLine("| 年份 | 国家 | 仪式总数 |"); Console.WriteLine("|------|------------|----------|"); // 遍历结果打印每行数据 foreach (var stat in ceremonyStats) { Console.WriteLine($"| {stat.Year} | {stat.Country,-10} | {stat.TotalCeremonies,8} |"); }
控制台输出效果示例:
| 年份 | 国家 | 仪式总数 |
|---|---|---|
| 2010 | Pakistan | 15 |
| 2010 | India | 22 |
| 2011 | Pakistan | 18 |
| 2012 | India | 25 |
内容的提问来源于stack exchange,提问作者Muhammad zubair
相关产品推荐
相关产品推荐

