C# 如何计算对象列表中的项目数?
我有一个对象类:C# 如何计算对象列表中的项目数?,c#,linq,C#,Linq,我有一个对象类: 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) {
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)};
}
公共类国家
{
公共字符串名称{get;}
公共int Land{get;}
公共列表资源{get;}
公共国家/地区(字符串名称、int-land、列表资源)
{
名称=名称;
土地=土地;
资源=资源;
}
公共静态列表GetCountries()
{
返回新列表()
{
新国家(“委内瑞拉”,882050,
新名单{“石油”、“天然气”、“铁矿石”、“黄金”、“铝土矿”、“其他矿物”、“水电”、“钻石”}),
新国家(“秘鲁”,127006,
新名单{“铜”、“银”、“金”、“石油”、“木材”、“鱼”、“铁矿石”、“煤”、“磷酸盐”、“钾盐”、“水电”、“天然气”}),
新国家(“巴拉圭”,397302,
新名单{“水电”、“木材”、“铁矿石”、“锰”、“石灰石”})
};
}
公共重写字符串ToString()=>
$“\n{Name}{Land}\n资源:{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());
}
List countries=Country.GetCountries();
列表国家资源描述(国家);
静态无效列表国家资源描述(列表国家)
{
i数不清的国家=
从乡下到乡下
orderby country.Resources.Count()递减
选择国家;
Console.WriteLine(“根据资源数量对国家进行排序:”);
foreach(分类国家中的国家)
Console.WriteLine(country.Name+“”+country.Resources.Count());
}
但我收到一条错误消息:
CS1061:“Country”不包含“resorceNum”的定义,并且找不到接受类型为“Country”的第一个参数的可访问扩展方法“resourceNum”(是否缺少using指令或程序集引用?)
如果您有任何见解,我们将不胜感激。您需要的LINQ查询如下:
from country in countries
orderby country.Resources.Count() descending
select country;
正如错误消息所暗示的那样,type
Country
上没有任何关于resorceNum
的定义。typeCountry
有一个类型为list
的资源列表,这就是您需要检查其大小以进行所描述的排序的原因。尝试以下操作:orderby resorceNum降序
,而不是resourceNum
是一个变量,不是类country
的属性。您需要返回一个新类型,而不是country
-country没有资源属性计数。您可以使用select new{country,resorceNum}返回一个匿名类型
(我会正确拼写resource或重命名为ResourceCount
)您需要更加小心拼写。resourceNum
和resourceNum
完全不同