共计 2122 个字符,预计需要花费 6 分钟才能阅读完成。
导读 | 这篇文章介绍了 C# 中对集合排序的三种方式,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下 |
对集合排序,可能最先想到的是使用 OrderBy 方法。
class Program
{static void Main(string[] args)
{IEnumerable result = GetStudents().OrderBy(r => r.Score);
foreach (var item in result)
{Console.WriteLine(item.Name + "--" + item.Score);
}
Console.ReadKey();}
private static List GetStudents()
{return new List ()
{new Student(){Id = 1, Name = "张三",Age = 15, Score = 80},
new Student(){Id = 2, Name = "李四",Age = 16, Score = 70},
new Student(){Id = 3, Name = "赵武",Age = 14, Score = 90}
};
}
}
public class Student
{public int Id { get; set;}
public string Name {get; set;}
public int Age {get; set;}
public int Score {get; set;}
}
以上,OrderBy 返回的类型是 IEnumerable
如果想使用 List
class Program
{static void Main(string[] args)
{List result = GetStudents();
result.Sort();
foreach (var item in result)
{Console.WriteLine(item.Name + "--" + item.Score);
}
Console.ReadKey();}
private static List GetStudents()
{return new List ()
{new Student(){Id = 1, Name = "张三",Age = 15, Score = 80},
new Student(){Id = 2, Name = "李四",Age = 16, Score = 70},
new Student(){Id = 3, Name = "赵武",Age = 14, Score = 90}
};
}
}
public class Student : IComparable
{public int Id { get; set;}
public string Name {get; set;}
public int Age {get; set;}
public int Score {get; set;}
public int CompareTo(Student other)
{return this.Score.CompareTo(other.Score);
}
}
让 Student 实现 IComparable
class Program
{static void Main(string[] args)
{List result = GetStudents();
result.Sort(new StudentSorter());
foreach (var item in result)
{Console.WriteLine(item.Name + "--" + item.Score);
}
Console.ReadKey();}
private static List GetStudents()
{return new List ()
{new Student(){Id = 1, Name = "张三",Age = 15, Score = 80},
new Student(){Id = 2, Name = "李四",Age = 16, Score = 70},
new Student(){Id = 3, Name = "赵武",Age = 14, Score = 90}
};
}
}
public class Student
{public int Id { get; set;}
public string Name {get; set;}
public int Age {get; set;}
public int Score {get; set;}
}
public class StudentSorter : IComparer
{public int Compare(Student x, Student y)
{return x.Score.CompareTo(y.Score);
}
}
综上,如果我们想对一个集合排序,大致有三种方式:
正文完
星哥说事-微信公众号
![post-qrcode](https://www.xgss.net/wp-content/uploads/2023/07/二维码-微信公众号256x256.jpg)