首页 > 解决方案 > 如何计算对象列表中的项目?

问题描述

我有一个对象类:

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 指令或程序集引用?)

任何见解将不胜感激。

标签: c#linq

解决方案


您需要的 LINQ 查询如下:

from country in countries
orderby country.Resources.Count() descending
select country;

resorceNum由于错误消息暗示on type没有任何定义Country。该类型Country有一个类型资源列表,List<String>这就是您需要检查其大小以进行您描述的排序的内容。


推荐阅读