我需要使用LINQ对此集合中的国家/地区进行排序:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp5
{
class Program
{
class Country
{
public string Name { get; set; }
public int Population { get; set; }
public Country(string name, int population)
{
Name = name;
Population = population;
}
}
static void Main(string[] args)
{
Country[] countryCollection =
{
new Country("Afghanistan", 34656032),
new Country("Austria", 8857960),
new Country("Brazil", 210147125),
new Country("Denmark", 5789957),
new Country("Russia", 144526636),
new Country("China", 1403500365),
new Country("Turkey", 80810525),
new Country("Serbia", 7001444),
new Country("Iraq", 37202572),
new Country("San Marino", 33344)
};
}
}
}它应该按人口排序,并以这种方式打印。
发布于 2019-02-21 03:38:45
这应该可以做你想要的事情
class Program
{
static void Main(string[] args)
{
List<Country> countryCollection = new List<Country>() {
new Country("Afghanistan",34656032),
new Country("Austria", 8857960),
new Country("Brazil", 210147125),
new Country("Denmark", 5789957),
new Country("Russia", 144526636),
new Country("China", 1403500365),
new Country("Turkey", 80810525),
new Country("Serbia", 7001444),
new Country("Iraq", 37202572),
new Country("San Marino", 33344) };
var OrderedCountries = countryCollection.OrderByDescending(x => x.Population).ToList();
foreach (var country in OrderedCountries)
{
Console.WriteLine($"The country {country.Name} has {country.Population} people");
}
}
}
public class Country
{
public string Name { get; set; }
public int Population { get; set; }
public Country(string name, int population)
{
Name = name;
Population = population;
}
}发布于 2019-02-21 04:01:17
你可以使用一个列表,或者如果你想维护一个数组,你可以使用一个委托给匿名方法:
static void Main(string[] args)
{
Country[] countryCollection = {
new Country("Afghanistan", 34656032),
new Country("Austria", 8857960),
new Country("Brazil", 210147125),
new Country("Denmark", 5789957),
new Country("Russia", 144526636),
new Country("China", 1403500365),
new Country("Turkey", 80810525),
new Country("Serbia", 7001444),
new Country("Iraq", 37202572),
new Country("San Marino", 33344)
};
Array.Sort(countryCollection, delegate(Country country1, Country country2) {
return country1.Population.CompareTo(country2.Population);
});
foreach (Country country in countryCollection) Console.WriteLine("Country name: " + country.Name + " Population: " + country.Population);
Console.ReadKey();
}有关更多详细信息,请参阅http://www.csharp-examples.net/sort-array/。
发布于 2019-02-21 10:40:02
您可以将数组转换为列表,按填充进行排序,然后将其转换回数组。
countryCollection = countryCollection.ToList().OrderBy(x => x.Population).ToArray();或者,如果您想要按人口降序进行排序:
countryCollection = countryCollection.ToList().OrderByDescending(x => x.Population).ToArray();https://stackoverflow.com/questions/54793891
复制相似问题