C# Как отсортировать несколько объектов - PullRequest
0 голосов
/ 04 февраля 2020
  1. Спросите пользователя, сколько продавцов он хочет назначить.

  2. Получите имя продавца, идентификатор, город и сколько яблок, которые он продал, для каждого продавец он хотел назначить.

  3. Создать 4 уровня в зависимости от того, сколько яблок продано. уровень 1 под 50 яблок, уровень 2 между 50-99 яблоками, уровень 3 между 100-199 яблоками и уровень 4 более 199 яблок.

  4. Когда все продавцы назначены, рассортируйте каждого человека по тому, как много яблок, которые они продали, от низкого до высокого.

  5. Распечатайте информацию о каждом продавце (имя, идентификатор, город, яблоки проданы) и на каком уровне они находятся и сколько продавцов там на том же уровне.

Пример:

name: daniel
id: 18886
city: chicago
apples sold: 30
1 seller have reached level 1: under 50 apples


name: elno
id: 18843
city: chicago
apples sold: 212

name: noel
id: 1567
city: chicago
apples sold: 230
2 seller have reached level 4: over 199 apples

Вот так выглядит мой код, я просто не знаю, как отсортировать все соответствующим образом при его записи на консоли

public class Seller 
{
    public string Name { get; set; }
    public int Id { get; set; }
    public string City { get; set; }
    public int Apples { get; set; } 

}
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hi and Welcome to The Garden!");
        Console.WriteLine("How many sellers would u like to assign?");

        int Assign = int.Parse(Console.ReadLine());

        Seller[] NewSeller = new Seller[Assign];

        for (int i = 0; i < Assign; i++) 
        {

            NewSeller[i] = new Seller();

            Console.WriteLine("______________________________");

            Console.Write("Enter name for seller" + i + "\nName: ");
            NewSeller[i].Name = Console.ReadLine();

            Console.Write("Enter id for seller " + i + "\nID; ");
            NewSeller[i].Id = int.Parse(Console.ReadLine());

            Console.Write("Enter city for seller " + i + "\nCity: ");
            NewSeller[i].City = Console.ReadLine();

            Console.Write("Enter apples sold for seller " + i + "\nApples: ");
            NewSeller[i].Apples = int.Parse(Console.ReadLine());

        }

        for (int i = 0; i < Assign; i++)
        {
            Console.WriteLine("__________________________________________________________");
            Console.WriteLine("|   Seller {0} |" , i);
            Console.WriteLine("|--------------");
            Console.WriteLine("| Name: {0}", NewSeller[i].Name);
            Console.WriteLine("| ID: {0}", NewSeller[i].Id);
            Console.WriteLine("| City: {0}", NewSeller[i].City);
            Console.WriteLine("| Apples sold: {0}", NewSeller[i].Apples);
            Console.WriteLine("__________________________________________________________");

        }
    }
}

Ответы [ 2 ]

0 голосов
/ 04 февраля 2020

Вы можете использовать Linq, чтобы отсортировать продавца и получить детали уровня

//Sort the seller and get the Level details
var results = sellers.OrderBy(s => s.Apples)
                     .Select(x => new
                            {
                                x.Name,
                                x.Id,
                                x.City,
                                x.Apples,
                                Level = x.Apples < 50 ? 1 : x.Apples < 99 ? 2 : x.Apples < 199 ? 3 : 4,
                                LevelDetails = x.Apples < 50 ? "under 50" : x.Apples < 99 ? "over 50" : x.Apples < 199 ? "over 99" : "over 199"
                        }); 

//Iterate the sorted list
foreach (var result in results)
{
    Console.WriteLine("__________________________________________________________");
    Console.WriteLine("|   Seller {0} |", results.ToList().IndexOf(result) + 1);
    Console.WriteLine("|--------------");
    Console.WriteLine("| Name: {0}", result.Name);
    Console.WriteLine("| ID: {0}", result.Id);
    Console.WriteLine("| City: {0}", result.City);
    Console.WriteLine("| Apples sold: {0}", result.Apples);
    Console.WriteLine("| {0} seller have reached level {1}: over {2} apples", results.Where(x=>x.Level==result.Level).Count(), result.Level, result.LevelDetails);
    Console.WriteLine("__________________________________________________________");
}
0 голосов
/ 04 февраля 2020

Это похоже на домашнее задание:)

Самый простой способ сортировки коллекций - с помощью LINQ через лямбда-выражение:

https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.orderby?view=netframework-4.8

Я бы также порекомендовал использовать интерполяцию строк, так как она более краткая и понятная:

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated

В вашем случае вы бы сделали что-то вроде это:

public class Seller 
{
    public string Name { get; set; }
    public int Id { get; set; }
    public string City { get; set; }
    public int Apples { get; set; }



}
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hi and Welcome to The Garden!");
        Console.WriteLine("How many sellers would u like to assign?");

        int Assign = int.Parse(Console.ReadLine());
        Seller[] NewSeller = new Seller[Assign];

        for (int i = 0; i < Assign; i++)
        {
            NewSeller[i] = new Seller();

            Console.WriteLine("______________________________");
            Console.Write($"Enter name for seller {i}: ");
            NewSeller[i].Name = Console.ReadLine();

            Console.Write($"Enter id for seller {i}: ");
            NewSeller[i].Id = int.Parse(Console.ReadLine());

            Console.Write($"Enter city for seller {i}: ");
            NewSeller[i].City = Console.ReadLine();

            Console.Write($"Enter apples sold for seller {i}: ");
            NewSeller[i].Apples = int.Parse(Console.ReadLine());
        }

        //default sorting is ascending, so low to high. use OrderByDescending when you need high to low
        Seller[] sortedList = NewSeller.OrderBy(s => s.Apples).ToArray();
        for (int i = 0; i < sortedList.Length; i++)
        {
            Seller currentSeller = sortedList[i];
            Console.WriteLine("__________________________________________________________");
            Console.WriteLine($"|   Seller {i} |");
            Console.WriteLine("|--------------");
            Console.WriteLine($"| Name: {currentSeller.Name}");
            Console.WriteLine($"| ID: {currentSeller.Id}");
            Console.WriteLine($"| City: {currentSeller.City}");
            Console.WriteLine($"| Apples sold: {currentSeller.Apples}");
            Console.WriteLine("__________________________________________________________");
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...