- using System;
- using System.Collections;
- using System.Collections.Generic;
- namespace LinqDemo1 {
- class Program {
- static void Main(string[] args) {
- Person[] persons = {
- new Person {
- FirstName = "Damon",
- LastName = "Hill"
- },
- new Person {
- FirstName = "Niki",
- LastName = "Lauda"
- },
- new Person {
- FirstName = "Ayrton",
- LastName = "Senna"
- }
- };
- Array.Sort(persons, new PersonComparer(PersonCompareType.FirstName));
- foreach(var p in persons) {
- Console.WriteLine(p);
- }
- Console.ReadKey();
- }
- }
- public enum PersonCompareType {
- FirstName,
- LastName
- }
- public class PersonComparer: IComparer {
- private PersonCompareType compareType;
- public PersonComparer(PersonCompareType compareType) {
- this.compareType = compareType;
- }
- public int Compare(Person x, Person y) {
- if (x == null && y == null) return 0;
- if (x == null) return 1;
- if (y == null) return - 1;
- switch (compareType) {
- case PersonCompareType.FirstName:
- return string.Compare(x.FirstName, y.FirstName);
- case PersonCompareType.LastName:
- return string.Compare(x.LastName, y.LastName);
- default:
- throw new ArgumentException("unexpected compare type");
- }
- }
- }
- public class Person {
- public override string ToString() {
- return string.Format("{0} {1}", FirstName, LastName);
- }
- public string FirstName {
- get;
- set;
- }
- public string LastName {
- get;
- set;
- }
- }
- }
来源: http://www.bubuko.com/infodetail-1970591.html