using System;
using System.Linq;
namespace Linq实现对象排序
{
class Program
{//今天终于找到了一种用Linq实现的排序方式
public static void Main(string[] args)
{
Person p1=new Person(50,"TD");
Person p2=new Person(30,"WD");
Person p3=new Person(40,"MD");
Person p4=new Person(20,"ND");
Person[] P=new Person[]{p1,p2,p3,p4};
Console.WriteLine("----------------排序之前------------------");
Display(P);
var RP = P.OrderBy(t=>t.Age);//用Lamda表达式进行正序排列
Console.WriteLine("----------------排序之后------------------");
foreach(Person p in RP)
{
Console.WriteLine(p);
}
Console.ReadKey(true);
}/// <summary>
/// 实现Person对象数组的输出
/// </summary>
/// <param name="P"></param>
static void Display(Person[] P)
{
for(int i=0;i<P.Length;i++)
{
Console.WriteLine(P);
}
}
}
/// <summary>
/// 定义一个Person类
/// </summary>
class Person
{
public Person(int age,string name)
{
Age=age;
Name=name;
}
public int Age{get;set;}
public string Name{get;set;}
public override string ToString()
{
return Name+"的年龄是:"+Age;
}
}
} |