PFranchise
PFranchise

Reputation: 6752

C# list.Orderby descending

I would like to receive a List sorted by Product.Name in descending order.

Similar to the function below which sorts the list in ascending order, just in reverse, is this possible?

var newList = list.OrderBy(x => x.Product.Name).ToList();

Upvotes: 187

Views: 467672

Answers (7)

Robb Hoff
Robb Hoff

Reputation: 1910

2 options for sorting a List in decending order

Method 1 Order against a specified key using OrderByDescending()

List<Product> myList = new() {
    new Product("A"),
    new Product("Z"),
    new Product("C")
};
myList = myList.OrderByDescending(x => x.Name).ToList();
Debug.WriteLine(
    $"{myList[0].Name}" + // 'Z'
    $"{myList[1].Name}" + // 'C'
    $"{myList[2].Name}"   // 'A'
);

Example Product

class Product
{
    public string Name { get; private set; }
    public Product(string Name)
    {
        this.Name = Name;
    }
}

Method 2 Sort ascending and use Reverse()

myList = myList.OrderBy(x => x.Name).ToList();
myList.Reverse();

Reverse() is convenient for generic types such as List<string>

Reverse sort a string list

List<string> stringList= new() { "A", "Z", "C" };
stringList.Sort();
stringList.Reverse();

Upvotes: 1

Basheer AL-MOMANI
Basheer AL-MOMANI

Reputation: 15327

look it this piece of code from my project

I'm trying to re-order the list based on a property inside my model,

 allEmployees = new List<Employee>(allEmployees.OrderByDescending(employee => employee.Name));

but I faced a problem when a small and capital letters exist, so to solve it, I used the string comparer.

allEmployees.OrderBy(employee => employee.Name,StringComparer.CurrentCultureIgnoreCase)

Upvotes: 4

Beedjees
Beedjees

Reputation: 295

var newList = list.OrderBy(x => x.Product.Name).Reverse()

This should do the job.

Upvotes: 17

StriplingWarrior
StriplingWarrior

Reputation: 156534

Sure:

var newList = list.OrderByDescending(x => x.Product.Name).ToList();

Doc: OrderByDescending(IEnumerable, Func).

In response to your comment:

var newList = list.OrderByDescending(x => x.Product.Name)
                  .ThenBy(x => x.Product.Price)
                  .ToList();

Upvotes: 325

Archana
Archana

Reputation: 11

list = new List<ProcedureTime>(); sortedList = list.OrderByDescending(ProcedureTime=> ProcedureTime.EndTime).ToList();

Which works for me to show the time sorted in descending order.

Upvotes: -2

asleep
asleep

Reputation: 4084

list.OrderByDescending();

works for me.

Upvotes: 13

Mark Byers
Mark Byers

Reputation: 838336

Yes. Use OrderByDescending instead of OrderBy.

Upvotes: 26

Related Questions