1、OrderBy操作符
OrderBy
操作符用于对输入序列中的元素进行排序,排序基于一个委托方法的返回值顺序,排序过程完成后,会返回一个类型为IOrderEnumerable<T>
的集合对象。
例如,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
List<People> pList = new List<People>();
People p1 = new People(1, "C", 4);
People p2 = new People(2, "Java", 7);
People p3 = new People(3, "Python", 11);
People p4 = new People(4, "Linux", 15);
People p5 = new People(5,"CJavaPY",1);
pList.Add(p1);
pList.Add(p2);
pList.Add(p3);
pList.Add(p4);
pList.Add(p5);
List<People> pList1 = new List<People>();
IEnumerable<People> newList = pList.OrderBy(p => p.Age);
foreach (var item in newList)
{
Console.WriteLine(item.Name);
}
AgeComparer ac = new AgeComparer();
IEnumerable<People> newList1 = pList.OrderBy(p => p.Age, ac);
Console.WriteLine();
foreach (var item in newList1)
{
Console.WriteLine(item.Name);
}
Console.ReadKey();
}
}
public class People
{
public People(int id, string name, int age)
{
this.Id = id;
this.Name = name;
this.Age = age;
}
public int Id
{
get;
set;
}
public string Name
{
get;
set;
}
public int Age
{
get;
set;
}
}
public class AgeComparer : IComparer<int>
{
public int Compare(int a1, int a2)
{
if (a1 > a2)
{
return (-1); //表示a1 > a2
}
else if (a1 < a2)
{
return (1); //表示a1 < a2
}
else
{
return (0); //表示a1=a2
}
}
}
}
2、OrderByDescending操作符
OrderByDescending
操作符的功能与OrderBy
操作符基本相同,二者只是排序的方式不同OrderBy
是顺序排序,而OrderByDescending
则是逆序排序。
例如,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
List<People> pList = new List<People>();
People p1 = new People(1, "C", 4);
People p2 = new People(2, "Java", 7);
People p3 = new People(3, "Python", 11);
People p4 = new People(4, "Linux", 15);
People p5 = new People(5,"CJavaPY",1);
pList.Add(p1);
pList.Add(p2);
pList.Add(p3);
pList.Add(p4);
pList.Add(p5);
List<People> pList1 = new List<People>();
IEnumerable<People> newList = pList.OrderByDescending(p => p.Age); //倒序
foreach (var item in newList)
{
Console.WriteLine(item.Name);
}
Console.ReadKey();
}
}
public class People
{
public People(int id, string name, int age)
{
this.Id = id;
this.Name = name;
this.Age = age;
}
public int Id
{
get;
set;
}
public string Name
{
get;
set;
}
public int Age
{
get;
set;
}
}
}