Reputation: 6752
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
Reputation: 1910
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
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
Reputation: 295
var newList = list.OrderBy(x => x.Product.Name).Reverse()
This should do the job.
Upvotes: 17
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
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