当使用C#Linq时,我们常常需要在对数据进行排序时使用OrderByDescending()方法。这个方法可以根据指定的条件对数据进行降序排序。
下面是使用OrderByDescending()方法的完整攻略:
格式
var result = collection.OrderByDescending(item => item.Property);
其中,collection是一个IEnumerable
示例1
假设我们有一个存储学生信息的Student类:
public class Student
{
public string Name { get; set; }
public int Age { get; set; }
public int Grade { get; set; }
}
现在我们有一个Student集合,需要按照学生的年龄进行降序排序:
List<Student> students = new List<Student>
{
new Student { Name = "Tom", Age = 20, Grade = 85 },
new Student { Name = "Jerry", Age = 19, Grade = 80 },
new Student { Name = "Jim", Age = 21, Grade = 95 },
new Student { Name = "Frank", Age = 18, Grade = 75 },
new Student { Name = "Bob", Age = 22, Grade = 90 },
};
var sortedStudents = students.OrderByDescending(s => s.Age);
这样就按照Age的降序排列了。
示例2
现在我们有一个存储音乐信息的Music类:
public class Music
{
public string Name { get; set; }
public string Singer { get; set; }
public int Views { get; set; }
}
现在我们有一个Music的集合,需要按照音乐视频播放量进行降序排序:
List<Music> musics = new List<Music>
{
new Music { Name = "Better With You", Singer = "Austin Mahone", Views = 230000 },
new Music { Name = "Can't Stop the Feeling", Singer = "Justin Timberlake", Views = 5600000 },
new Music { Name = "Cheyenne", Singer = "Jason Derulo", Views = 23000000 },
new Music { Name = "Cheap Thrills", Singer = "Sia", Views = 330000000 },
new Music { Name = "Closer", Singer = "The Chainsmokers", Views = 11000000 },
};
var sortedMusics = musics.OrderByDescending(m => m.Views);
这样就按照Views的降序排列了。
以上就是使用C#Linq的OrderByDescending()方法的完整攻略。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:C# Linq的OrderByDescending()方法 – 根据指定的键按降序对序列的元素进行排序 - Python技术站