如何用LINQ筛选含至少3个城市的随机国家的城市列表?
针对城市列表处理的LINQ解决方案
1. 筛选包含至少3个城市的分组
在GroupBy之后通过Where筛选分组的元素数量即可,直接判断分组的Count()是否大于等于3:
List<City> cities = AssumeWeHaveAPopulatedList(); // 筛选出符合条件的国家分组 var validCountryGroups = cities.GroupBy(c => c.country) .Where(group => group.Count() >= 3);
2. 随机选择符合条件的分组并展开为城市列表
先把符合条件的分组转为列表(方便随机访问),再用Random生成随机索引选中目标分组,最后将分组转为城市列表:
var random = new Random(); var validGroups = validCountryGroups.ToList(); if (validGroups.Any()) { // 随机选中一个符合条件的分组 var selectedGroup = validGroups[random.Next(validGroups.Count)]; // 将分组展开为城市列表 List<City> targetCities = selectedGroup.ToList(); }
注意:Random实例建议只创建一次,避免短时间内多次调用生成重复随机数。
3. 无需先分组的替代方案
可以先统计每个国家的城市数量,筛选出符合条件的国家后再随机选择并提取对应城市,比如用字典手动统计:
var random = new Random(); List<City> cities = AssumeWeHaveAPopulatedList(); // 第一步:统计每个国家的城市数量 var countryCityCount = new Dictionary<string, int>(); foreach (var city in cities) { if (countryCityCount.ContainsKey(city.country)) countryCityCount[city.country]++; else countryCityCount[city.country] = 1; } // 第二步:筛选出城市数≥3的国家 var validCountries = countryCityCount.Where(kv => kv.Value >= 3) .Select(kv => kv.Key) .ToList(); // 第三步:随机选国家并提取对应城市 if (validCountries.Any()) { var selectedCountry = validCountries[random.Next(validCountries.Count)]; List<City> targetCities = cities.Where(c => c.country == selectedCountry).ToList(); }
也可以用LINQ直接筛选符合条件的国家集合,再随机选择:
var validCountries = cities.Select(c => c.country) .Distinct() .Where(country => cities.Count(c => c.country == country) >= 3) .ToList(); if (validCountries.Any()) { var selectedCountry = validCountries[random.Next(validCountries.Count)]; var targetCities = cities.Where(c => c.country == selectedCountry).ToList(); }
不过这种方式会多次遍历原城市列表,数据量较大时效率不如分组或字典统计的方案。
内容的提问来源于stack exchange,提问作者user2015253
相关产品推荐
相关产品推荐

