欢迎光临

木子屋

标题: 实现List&lt;T&gt;元素排序两种方法

作者: dnawo

日期: 2012-09-28 06:18 PM

分类: Win编程

内容: 1.调用Sort(Comparison<T> comparison)
复制内容到剪贴板 程序代码using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
/// <summary>
/// 排序方法
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public static int FunCompare(Person x, Person y)
{
return x.Age.CompareTo(y.Age);
}
static void Main(string[] args)
{
List<Person> people = new List<Person>();
people.Add(new Person() { Name = "person1", Age = 20 });
people.Add(new Person() { Name = "person2", Age = 50 });
people.Add(new Person() { Name = "person3", Age = 30 });
//排序
people.Sort(FunCompare); //或：people.Sort((x, y) => x.Age.CompareTo(y.Age));
foreach (Person person in people)
Console.WriteLine("{0},{1}", person.Name, person.Age);
Console.ReadKey();
}
}
}
2.调用Sort(IComparer<T> comparer)
复制内容到剪贴板 程序代码using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
/// <summary>
/// 排序类
/// </summary>
class ClsCompare : IComparer<Person>
{
public int Compare(Person x, Person y)
{
return x.Age.CompareTo(y.Age);
}
}
class Program
{
static void Main(string[] args)
{
List<Person> people = new List<Person>();
people.Add(new Person() { Name = "person1", Age = 20 });
people.Add(new Person() { Name = "person2", Age = 50 });
people.Add(new Person() { Name = "person3", Age = 30 });
//排序
people.Sort(new ClsCompare());
foreach (Person person in people)
Console.WriteLine("{0},{1}", person.Name, person.Age);
Console.ReadKey();
}
}
}

+ 查看当前日志评论 (0)

登录

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 6.391 ms

返回

标题: 实现List&lt;T&gt;元素排序两种方法

你没有权限发表评论

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 6.391 ms

返回

暂无评论

返回

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 7.208 ms

返回