一、 对数组进行排序
最常见的排序是对一个数组排序,比如:
int[] aArray = new int[8] { 18, 17, 21, 23, 11, 31, 27, 38 };
1、利用冒泡排序进行排序:
(即每个值都和它后面的数值比较,每次拿出最小值)
static void Main(string[] args)
{
int[] aArray = new int[8] { 18, 17, 21, 23, 11, 31, 27, 38 };
for (int j = 0; j < aArray.Length - 1; j++)
{
for (int i = 0; i < aArray.Length - 1; i++)
{
if (aArray[i] > aArray[i + 1])
{
int temp = aArray[i];
aArray[i] = aArray[i + 1];
aArray[i + 1] = temp;
}
}
}
foreach (var a in aArray)
{
Console.Write($"{a} ");
}
Console.ReadKey();
}
运行结果:
2、利用Array.Sort排序:
1升序
static void Main(string[] args)
{
int[] aArray = new int[8] { 18, 17, 21, 23, 11, 31, 27, 38 };
Array.Sort(aArray);
foreach (var a in aArray)
{
Console.Write($"{a} ");
}
Console.ReadKey();
}
运行结果:
2降序:
先升序排列,然后对数组反转
static void Main(string[] args)
{
int[] aArray = new int[8] { 18, 17, 21, 23, 11, 31, 27, 38 };
Array.Sort(aArray);//数组排序(默认升序)
Array.Reverse(aArray);//数组反转
foreach (var a in aArray)
{
Console.Write($"{a} ");
}
Console.ReadKey();
}
运行结果:
二、对List进行排序
大多数时候,我们需要将list集合里面的数据进行排序,
1、利用List<T> 自带的Sort排序方法
1 、升序排序
aList.Sort();
2、降序排序
aList.Sort();//升序
aList.Reverse();//反转
3 sort也可以用如下方式操作:
list.Sort((a, b) => a.CompareTo(b));//升序
list.Sort((a, b) => b.CompareTo(a));//降序
2、利用List的OrderBy与OrderByDescending方法
升序排列:
List<int> aList = new List<int> { 18, 17, 21, 23, 11, 31, 27, 38 };
aList = aList.OrderBy(a => a).ToList();
降序排列:
List<int> aList = new List<int> { 18, 17, 21, 23, 11, 31, 27, 38 };
aList = aList.OrderByDescending(a => a).ToList();
利用link,这种感觉和方法二是一回事
List<int> aList = new List<int> { 18, 17, 21, 23, 11, 31, 27, 38 };
aList = (from a in aList orderby a ascending select a).ToList();//升序
aList = (from a in aList orderby a descending select a).ToList();//降序
如果集合里存放的是一个类型,比如:
学生类:
public class Student
{
public string name { get; set; }
public int age { get; set; }
public int score { get; set; }
public override string ToString()
{
return $"姓名是:{name},年龄是:{age},得分是:{score}";
}
}
方法一:stuList.Sort((x, y) => x.score.CompareTo(y.score));
static void Main(string[] args)
{
List<Student> stuList = new List<Student>
{
new Student() {name = "zyr", age = 23, score = 99},
new Student() {name = "zls", age = 25, score = 95},
new Student() {name = "zsq", age = 27, score = 100},
new Student() {name = "zlw", age = 15, score = 69},
new Student() {name = "ywe", age = 17, score = 72},
new Student() {name = "asw", age = 29, score = 58}
};
//方法1 升序
//stuList.Sort((x, y) => x.score.CompareTo(y.score));
stuList = stuList.OrderBy(stu=>stu.score).ToList();
foreach (var stu in stuList)
{
Console.WriteLine($"{stu}");
}
Console.ReadKey();
}
方法二: 加入这个学生成绩有重复的,对于重复的成绩按照年龄再排序:
方法1 升序
stuList.Sort((x, y) =>
{
int ret = x.score.CompareTo(y.score);
if (ret == 0)
{
return x.age.CompareTo(y.age);
}
else
{
return ret;
}
});
方法2 升序
stuList = stuList.OrderBy(stu => stu.score).ThenBy(stu => stu.age).ToList();