Sorting and Searching:Implementing IComparable : Compare « Collections Data Structure « 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 » Collections Data Structure » CompareScreenshots 
Sorting and Searching:Implementing IComparable
Sorting and Searching:Implementing IComparable


using System;

public class ImplementingIComparable {
    public static void Main()
    {
        Employee[] arr = new Employee[4];
        arr[0new Employee("A"1);
        arr[1new Employee("B"2);
        arr[2new Employee("C"4);
        arr[3new Employee("D"3);
        
        Array.Sort(arr);
        foreach (Employee emp in arr)
        Console.WriteLine("Employee: {0}", emp);
        
        // Find employee id 2 in the list;
        Employee employeeToFind = new Employee(null, 2);
        int index = Array.BinarySearch(arr, employeeToFind);
        if (index != -1)
        Console.WriteLine("Found: {0}", arr[index]);    
    }
}
public class Employee: IComparable
{
    public Employee(string name, int id)
    {
        this.name = name;
        this.id = id;
    }
    
    int IComparable.CompareTo(object obj)
    {
        Employee emp2 = (Employeeobj;
        if (this.id > emp2.id)
        return(1);
        if (this.id < emp2.id)
        return(-1);
        else
        return(0);
    }
    
    public override string ToString()
    {
        return(String.Format("{0}:{1}", name, id));
    }
    
    string    name;
    int    id;
}


           
       
Related examples in the same category
1.implements the IComparable interfaceimplements the IComparable interface
2.Use IComparerUse IComparer
3.Implement IComparableImplement IComparable
4.Sorting and Searching:Advanced Use of HashesSorting and Searching:Advanced Use of Hashes
5.Sorting and Searching:Using IComparerSorting and Searching:Using IComparer
6.Sorting and Searching:IComparer as a PropertySorting and Searching:IComparer as a Property
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.