C#中合并两个JSON文件 用LINQ查询2021年仪式最多的国家
解决方案
1. 定义Model类(匹配JSON结构)
先确保Model类字段与JSON文件对应,示例结构如下:
public class Country { public string Id { get; set; } public string FullName { get; set; } // JSON中其他属性按需添加 } public class Loc { public string CountryId { get; set; } // 其他位置相关属性按需添加 } public class Ceremony { public int Year { get; set; } public Loc Location { get; set; } // 其他仪式相关属性按需添加 }
2. 读取JSON并关联国家全名
使用System.Text.Json(或Newtonsoft.Json)读取文件,将仪式数据与国家数据关联,获取对应国家全名:
// 读取JSON数据 var countries = JsonSerializer.Deserialize<List<Country>>(File.ReadAllText("Country.json")); var ceremonies = JsonSerializer.Deserialize<List<Ceremony>>(File.ReadAllText("Ceremony.json")); // 生成包含国家全名的仪式集合 var ceremoniesWithCountry = ceremonies.Select(ceremony => new { CeremonyInfo = ceremony, CountryFullName = countries.FirstOrDefault(c => c.Id == ceremony.Location.CountryId)?.FullName ?? "未匹配到国家" });
3. LINQ查询2021年仪式最多的国家
通过分组统计+排序,找出2021年举办仪式数量最多的国家:
var topCountry = ceremonies .Where(c => c.Year == 2021) .GroupBy(c => c.Location.CountryId) .Select(group => new { CountryId = group.Key, CountryName = countries.FirstOrDefault(c => c.Id == group.Key)?.FullName ?? "未知国家", CeremonyCount = group.Count() }) .OrderByDescending(res => res.CeremonyCount) .FirstOrDefault(); // 输出结果 if (topCountry != null) { Console.WriteLine($"2021年举办仪式最多的国家:{topCountry.CountryName},共{topCountry.CeremonyCount}场"); }
注意事项
- 确保JSON文件路径正确,若文件不在程序根目录,需使用完整路径
- 如果存在多个国家仪式数量并列第一,可将
FirstOrDefault()改为Take(n)获取前n个国家
内容的提问来源于stack exchange,提问作者Zubair
相关产品推荐
相关产品推荐

