c# - 如何计算对象列表中的项目?
问题描述
我有一个对象类:
public class Country
{
public string Name { get; }
public int Land { get; }
public List<string> Resources { get; }
public Country(string name, int land, List<string> resources)
{
Name = name;
Land = land;
Resources = resources;
}
public static List<Country> GetCountries()
{
return new List<Country>()
{
new Country( "Venezuela", 882050,
new List<string> { "petroleum", "natural gas", "iron ore", "gold", "bauxite", "other minerals", "hydropower", "diamonds" }),
new Country( "Peru", 127006,
new List<string> { "copper", "silver", "gold", "petroleum", "timber", "fish", "iron ore", "coal", "phosphate", "potash", "hydropower", "natural gas"}),
new Country( "Paraguay", 397302,
new List<string> { "hydropower", "timber", "iron ore", "manganese", "limestone" })
};
}
public override string ToString() =>
$"\n{Name} {Land} \nResources: {string.Join(", ", Resources)};
}
在我的主目录中,我想使用 LINQ 根据他们拥有的自然资源的数量,按降序排列国家。我在想我需要计算每个对象内的资源,然后根据资源编号进行排序。到目前为止,我有这个:
List<Country> countries = Country.GetCountries();
ListCountriesResourceDesc(countries);
static void ListCountriesResourceDesc(List<Country> countries)
{
IEnumerable<Country> sortedCountries =
from country in countries
orderby country.Resources.Count() descending
select country;
Console.WriteLine("Sorted countries according to number of resources:");
foreach (Country country in sortedCountries)
Console.WriteLine(country.Name + " " + country.Resources.Count());
}
但我收到一条错误消息:
CS1061:“国家/地区”不包含“资源编号”的定义,并且找不到接受“国家/地区”类型的第一个参数的可访问扩展方法“资源编号”(您是否缺少 using 指令或程序集引用?)
任何见解将不胜感激。
解决方案
您需要的 LINQ 查询如下:
from country in countries
orderby country.Resources.Count() descending
select country;
resorceNum
由于错误消息暗示on type没有任何定义Country
。该类型Country
有一个类型资源列表,List<String>
这就是您需要检查其大小以进行您描述的排序的内容。
推荐阅读
- django - 如何使 django 管理站点依赖于我的自定义 Django Rest Framework 令牌身份验证?
- java - rootpreferences Android Studio 中的依赖关系
- php - 更改 PDO 设置后 PHP 重置自动增量功能不再起作用
- css - 活动时更改选项卡颜色
- algorithm - TDD 和动态规划
- python - 如何将 QMenuBar 的操作设置为多行(新行)
- reactjs - html 中的 Youtube 视频(检测视频是否已播放)
- ssh - How to setup ssh for vagrant box creation?
- android - 向 React Native 应用程序添加自定义字体 - 版本 > 0.60
- rust - 如何在不创建其他变量的情况下修复“创建一个仍在使用时释放的临时对象”?