一步一步从简单开始:
1.简单的单个数组/序列排序:
(a)直接使用Array.Sort
var array = new int[] { 3, 2, 4, 5, 6, 7, 1 };
Array.Sort(array); //对array排序
遍历输出:
foreach (var item in array)
Console.WriteLine(item);
Console.Read();
结果为:
1
2
3
4
5
6
7
(b)也可以先转化为List,再使用List.Sort()排序:
先转化为List,再用自带的List.Sort()排序
var array = new int[] { 3, 2, 4, 5, 6, 7, 1 };
var list = array.ToList(); //转化为list
list.Sort(); //使用默认比较器对list的元素排序
foreach (var item in list)
Console.WriteLine(item);
Console.Read();
输出:
1
2
3
4
5
6
7
2.元素较复杂的排序方法:
较复杂的元素,如类,也可以用2种方法排序
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
class Program
{
static void Main(string[] args)
{
List<Person> school = new List<Person>()
{
new Person(){ Id = 4, Name = "a"},
new Person(){ Id = 3, Name = "b"},
new Person(){ Id = 2, Name = "c"},
new Person(){ Id = 5, Name = "d"},
new Person(){ Id = 1, Name = "e"}
};
//1.使用List的OrderBy
Console.WriteLine("--------使用List的OrderBy--------");
var orders = school.OrderBy(x => x.Id);
foreach (var item in orders)
Console.WriteLine(item.Id + ":" + item.Name);
//2.使用Array.Sort和比较器比较进行排序
Console.WriteLine("--------构造比较器--------");
Console.WriteLine("--------使用Array.Sort比较--------");
Person[] array = school.ToArray();
Array.Sort(array, (now, next) =>
{
//return值含义(小于0:now小于next。 等于0:now等于next。 大于 0:now大于next)
return now.Id - next.Id;//此处now为前一个元素,next为后一元素,
});
foreach (var item in array)
Console.WriteLine(item.Id + ":" + item.Name);
Console.Read();
}
}
输出:
--------使用List的OrderBy--------
1:e
2:c
3:b
4:a
5:d
--------构造比较器--------
--------使用Array.Sort比较--------
1:e
2:c
3:b
4:a
5:d
3.单个序列去重排序
int[] array = new int[] { 3, 2, 4, 5, 6, 7, 7, 1, 1, 1, 1, 1, 1, 1 };
var orders = array.Distinct().OrderBy(x => x); //需引用:using System.Linq;
foreach (var item in orders)
Console.WriteLine(item);
Console.Read();
输出:
1
2
3
4
5
6
7
4.多个序列合并去重排序
使用Union先求并集,并集会把重复多余的去掉,省了Distinct,再用OrderBy排序
int[] array = new int[] { 3, 2, 4, 5, 6, 7, 7, 1, 1, 1, 1, 1, 1, 1 };
int[] another = new int[] { 10, 11, 12 };
var together = array.Union(another);//先求并集,会把重复元素合并为1个
var orders = together.OrderBy(x => x); //需引用:using System.Linq;
foreach (var item in orders)
Console.WriteLine(item);
Console.Read();
输出:
1
2
3
4
5
6
7
10
11
12