Implements IComparable : IComparable « Generics « C# / C Sharp

Home
C# / C Sharp
1.2D Graphics
2.Class Interface
3.Collections Data Structure
4.Components
5.Data Types
6.Database ADO.net
7.Design Patterns
8.Development Class
9.Event
10.File Stream
11.Generics
12.GUI Windows Form
13.Language Basics
14.LINQ
15.Network
16.Office
17.Reflection
18.Regular Expressions
19.Security
20.Services Event
21.Thread
22.Web Services
23.Windows
24.Windows Presentation Foundation
25.XML
26.XML LINQ
C# / C Sharp by API
C# / CSharp Tutorial
C# / CSharp Open Source
C# / C Sharp » Generics » IComparableScreenshots 
Implements IComparable
 


using System;
using System.Collections.Generic;

public class Book : IComparable<Book> {
    private string name;
    private int circulation;

    private class AscendingCirculationComparer : IComparer<Book> {
        public int Compare(Book x, Book y) {
            if (x == null && y == nullreturn 0;
            else if (x == nullreturn -1;
            else if (y == nullreturn 1;
            if (x == yreturn 0;
            return x.circulation - y.circulation;
        }
    }
    public Book(string name, int circulation) {
        this.name = name;
        this.circulation = circulation;
    }

    public static IComparer<Book> CirculationSorter {
        get return new AscendingCirculationComparer()}
    }

    public override string ToString() {
        return string.Format("{0}: Circulation = {1}", name, circulation);
    }

    public int CompareTo(Book other) {
        if (other == nullreturn 1;

        if (other == thisreturn 0;
        return string.Compare(this.name, other.name, true);
    }
}

public class MainClass {
    public static void Main() {
        List<Book> Books = new List<Book>();

        Books.Add(new Book("E"1));
        Books.Add(new Book("T"5));
        Books.Add(new Book("G"2));
        Books.Add(new Book("S"8));
        Books.Add(new Book("H"5));

        foreach (Book n in Books) {
            Console.WriteLine("  " + n);
        }

        Books.Sort();
        foreach (Book n in Books) {
            Console.WriteLine("  " + n);
        }

        Books.Sort(Book.CirculationSorter);
        foreach (Book n in Books) {
            Console.WriteLine("  " + n);
        }
    }
}

 
Related examples in the same category
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.