我想收到由List
按降序排序
的
Product.Name
。
类似于下面的函数,将列表按升序排序,只是相反,这可能吗?
var newList = list.OrderBy(x => x.Product.Name).ToList();
当然:
var newList = list.OrderByDescending(x => x.Product.Name).ToList();
Doc: OrderByDescending(IEnumerable, Func).
回复您的评论:
var newList = list.OrderByDescending(x => x.Product.Name)
.ThenBy(x => x.Product.Price)
.ToList();
var newList = list.OrderBy(x => x.Product.Name).Reverse()
这应该可以完成工作。
list.OrderByDescending();
对我有用。
看看我项目中的这段代码
我正在尝试根据模型中的属性重新排序列表,
allEmployees = new List<Employee>(allEmployees.OrderByDescending(employee => employee.Name));
但是当
small and capital letters exist
时我遇到了一个问题,所以为了解决它,我使用了字符串比较器。
allEmployees.OrderBy(employee => employee.Name,StringComparer.CurrentCultureIgnoreCase)
方法一使用LINQ方法
OrderByDescending()
List<Product> listToSort = new List<Product>
{
new Product("A"),
new Product("Z"),
new Product("C")
};
// Assign the list to itself (or use a new var if you need both versions)
listToSort = listToSort.OrderByDescending(x => x.Name).ToList();
Debug.WriteLine($"{listToSort[0].Name}"); // 'Z'
Debug.WriteLine($"{listToSort[1].Name}"); // 'C'
Debug.WriteLine($"{listToSort[2].Name}"); // 'A'
例子产品类别
class Product
{
public string Name { get; private set; }
public Product(string Name)
{
this.Name = Name;
}
}
方法 2 如果您已经知道如何按升序对列表进行排序,您可以使用
Reverse()
listToSort.Reverse();
Reverse()
对于 泛型类型 特别方便,例如 List<string>
或 List<int>
因为密钥是隐含的,它节省了为 OrderByDescending 方法编写 lambda 表达式。
反向排序泛型
List<string>
此代码无需上述任何内容即可工作。
List<string> stringList= new List<string> { "A", "Z", "C" };
stringList.Sort();
stringList.Reverse();
Debug.WriteLine($"{stringList[0]}"); // 'Z'
Debug.WriteLine($"{stringList[1]}"); // 'C'
Debug.WriteLine($"{stringList[2]}"); // 'A'
按多个键排序
如果您需要对多个键进行排序,您可以链接 System.Linq.Enumerable
中描述的排序方法List<Person> people = new List<Person>();
// Sort by last name in descending order, then by first name in descending order
List<Person> sortedPeople = people.OrderByDescending(p => p.LastName)
.ThenByDescending(p => p.FirstName)
.ToList();
list = new List<ProcedureTime>(); sortedList = list.OrderByDescending(ProcedureTime=> ProcedureTime.EndTime).ToList();
这对我有用,可以显示按降序排列的时间。