J'ai besoin de trier les pays de cette collection à l'aide de 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) }; } } }
3 Réponses :
Cela devrait faire ce que vous voulez
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; } }
Vous pouvez également utiliser la syntaxe LINQ vous donnant archico-Varcountries = de pays dans CountryCollection Order Pays.name Sélectionnez le pays; Code> (qui triera par nom de pays, ascendant)
Vous pouvez utiliser une liste ou si vous souhaitez maintenir un tableau, vous pouvez utiliser un délégué à une méthode anonyme: voir
Vous pouvez convertir le tableau en une liste, commandez-le par population, puis la convertir en une matrice.
countryCollection = countryCollection.ToList().OrderByDescending(x => x.Population).ToArray();
Avez-vous essayé Googling pour "Linq Tri"? Cela m'a amené à: Docs.Microsoft .Com / fr-US / DotNet / CSHARP / Guide de programmation / ... . L'exemple qu'ils affichent à l'aide de la propriété code> code> d'une chaîne code> code>, mais vous pouvez utiliser le nom
nom code> ou
Population Code> Propriétés de votre pays
code> s
Oui, mais cela n'accepte pas la population comme paramètre. COMPILER dit que cela n'existe pas dans le contexte actuel lorsque je le codie de cette façon.