Home > Net >  c# Please how to get an order liste in c#
c# Please how to get an order liste in c#

Time:11-28

Hi, please, how to get an ordered list in c#

string[] names = {"name1", "name2", "name3"};

I would like a result like this:

001 name1
002 name2
003 name3
etc ...

but not like this

1 name1
2 name2
3 name3
etc ...

I tried a while loop like:

string[] cars = {"name1", "name2", "name3"};


foreach (string i in cars) 
{
  Console.WriteLine(i);
}

but I want a result like

001 name1
002 name2
003 name3
etc ...

not only the names

CodePudding user response:

Use a for-loop in order to have an index

for (int i = 0; i < cars.Length; i  ) {
    Console.WriteLine($"{i   1:000} {cars[i]}");
}

Note that string i for a car is very confusing. It is usual to use the name i for integers. For a generic string name use s. But in your code string car would be more readable.

See also:


A different way would be to declare a Car class like this

public class Car
{
    public string Name { get; set; }
    
    public int Index { get; set; }

    public override string ToString()
    {
        return $"{Index:000} {Name}"
    }
}

Then you can create an array and print it like this

Car[] cars = {
    new Car { Name = "name", Index = 1 },
    new Car { Name = "other name", Index = 2 },
    new Car { Name = "yet another name", Index = 3 },
};

foreach (Car car in cars) 
{
  Console.WriteLine(car);
}

CodePudding user response:

Something like this

string[] cars = new[] { "name1", "name2", "name3" };

for (int i = 0; i < cars.Length; i  )
    Console.WriteLine($"{i:D3} {cars[i]}");

CodePudding user response:

You can simply use Array.Sort() method to sort an array.

string[] cars = {"name3", "name2", "name3"};
Array.Sort(cars);

for (int i = 0; i < cars.Length; i  )
Console.WriteLine($"{i:D3} {cars[i]}");

Output:

 001 name1
 002 name2
 003 name3
  • Related