Sort ArrayList with Custom Objects using IComparer in C# Or VB.NET

No.of Views5490
Bookmarked0 times
Downloads 
Votes0
By  RRaveen   On  29 Dec 2010 11:12:56
Tag : .NET Frameworks , General
In this article, I will explain how to sort Arraylist with custom object. Sometimes you may add custom objects within the ArrayList and need to sort using an attribute in custom object.
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

In this article, I will explain how to sort Arraylist with custom object. Sometimes you may add custom objects within the ArrayList and need to sort using an attribute in custom object.

Implementation

Step 1

Create new console type project using visual studio and add new class called Publisher.cs. Add four attribute to Publisher class. The class like shown below,

C# Code

using System;

/// <summary>
/// Summary description for Publisher
/// </summary>
public class Publisher
{
    public Publisher()
    {
        
    }
    public Publisher(string _name, string _address1, string _address2, string _company)
    {
        this.name = _name;
        this.company = _company;
        this.address1 = _address1;
        this.address2 = _address2;
    }

    string name;

    public string Name
    {
        get { return name; }
        set { name = value; }
    }
    string address1;

    public string Address1
    {
        get { return address1; }
        set { address1 = value; }
    }
    string address2;

    public string Address2
    {
        get { return address2; }
        set { address2 = value; }
    }
    string company;

    public string Company
    {
        get { return company; }
        set { company = value; }
    }
}

VB.NET Code

''' <summary>
''' Summary description for Publisher
''' </summary>
Public Class Publisher

	Public Sub New()
	End Sub
	Public Sub New(_name As String, _address1 As String, _address2 As String, _company As String)
		Me.m_name = _name
		Me.m_company = _company
		Me.m_address1 = _address1
		Me.m_address2 = _address2
	End Sub

	Private m_name As String

	Public Property Name() As String
		Get
			Return m_name
		End Get
		Set
			m_name = value
		End Set
	End Property
	Private m_address1 As String

	Public Property Address1() As String
		Get
			Return m_address1
		End Get
		Set
			m_address1 = value
		End Set
	End Property
	Private m_address2 As String

	Public Property Address2() As String
		Get
			Return m_address2
		End Get
		Set
			m_address2 = value
		End Set
	End Property
	Private m_company As String

	Public Property Company() As String
		Get
			Return m_company
		End Get
		Set
			m_company = value
		End Set
	End Property
End Class

Step 2
Then create new ArrayList object and add five publisher objects and print name attribute as output.

C# Code

ArrayList collectionOfPub = new ArrayList();
            collectionOfPub.Add(new Publisher("Wrox", "No-02,John Ave 2", "US", "WROX"));
            collectionOfPub.Add(new Publisher("Apress", "No-03,Cels Ave 6", "US", "APRESS"));
            collectionOfPub.Add(new Publisher("Sams", "No-89,Test Ave 32", "US", "SAMS"));
            collectionOfPub.Add(new Publisher("Orelly", "No-23/08,John Ave 23", "US", "ORELLY"));
            collectionOfPub.Add(new Publisher("Packtpub", "No-56,John Ave 5", "INDIA", "PACKTPUB"));

            foreach (Publisher item in collectionOfPub)
            {
                Console.WriteLine("{0}:{1}", "Name", item.Name);
            }

VB.NET Code

Dim collectionOfPub As New ArrayList()
collectionOfPub.Add(New Publisher("Wrox", "No-02,John Ave 2", "US", "WROX"))
collectionOfPub.Add(New Publisher("Apress", "No-03,Cels Ave 6", "US", "APRESS"))
collectionOfPub.Add(New Publisher("Sams", "No-89,Test Ave 32", "US", "SAMS"))
collectionOfPub.Add(New Publisher("Orelly", "No-23/08,John Ave 23", "US", "ORELLY"))
collectionOfPub.Add(New Publisher("Packtpub", "No-56,John Ave 5", "INDIA", "PACKTPUB"))

For Each item As Publisher In collectionOfPub
	Console.WriteLine("{0}:{1}", "Name", item.Name)
Next

Now run application and see output
Output 

Image Loading

In above output name is not sorted. So let’s implement to sort features to this publisher list.

Step 3
    In order to enable to sorting features to custom objects, the .NET Framework has two Interfaces such as,

1.    IComparable
2.    IComparer

IComparable
    Defines a generalized type-specific comparison method that a value type or class implements to order or sort its instances. This is most suitable for ArrayList
IComparer
    This interface is used in conjunction with the Array.Sort and Array.BinarySearch methods. It provides a way to customize the sort order of a collection. This is most suitable for Array.

Our demonstration is example is based with ArrayList, so let’s modify the Publisher class with inherit with IComparable. The modified publisher class as like below,

C# Code

using System;

/// <summary>
/// Summary description for Publisher
/// </summary>
public class Publisher : IComparable
{
    public Publisher()
    {

    }
    public Publisher(string _name, string _address1, string _address2, string _company)
    {
        this.name = _name;
        this.company = _company;
        this.address1 = _address1;
        this.address2 = _address2;
    }

    string name;

    public string Name
    {
        get { return name; }
        set { name = value; }
    }
    string address1;

    public string Address1
    {
        get { return address1; }
        set { address1 = value; }
    }
    string address2;

    public string Address2
    {
        get { return address2; }
        set { address2 = value; }
    }
    string company;

    public string Company
    {
        get { return company; }
        set { company = value; }
    }

    #region IComparable Members

    public int CompareTo(object obj)
    {
        if (this.GetType() != obj.GetType())
        {
            throw new ApplicationException("The object are not same type");
        }
        return this.name.CompareTo(((Publisher)obj).name);
    }

    #endregion

}

VB.NET Code

''' <summary>
''' Summary description for Publisher
''' </summary>
Public Class Publisher
	Implements IComparable

	Public Sub New()
	End Sub
	Public Sub New(_name As String, _address1 As String, _address2 As String, _company As String)
		Me.m_name = _name
		Me.m_company = _company
		Me.m_address1 = _address1
		Me.m_address2 = _address2
	End Sub

	Private m_name As String

	Public Property Name() As String
		Get
			Return m_name
		End Get
		Set
			m_name = value
		End Set
	End Property
	Private m_address1 As String

	Public Property Address1() As String
		Get
			Return m_address1
		End Get
		Set
			m_address1 = value
		End Set
	End Property
	Private m_address2 As String

	Public Property Address2() As String
		Get
			Return m_address2
		End Get
		Set
			m_address2 = value
		End Set
	End Property
	Private m_company As String

	Public Property Company() As String
		Get
			Return m_company
		End Get
		Set
			m_company = value
		End Set
	End Property

	#Region "IComparable Members"

	Public Function CompareTo(obj As Object) As Integer Implements IComparable.CompareTo
		If Me.[GetType]() IsNot obj.[GetType]() Then
			Throw New ApplicationException("The object are not same type")
		End If
		Return Me.m_name.CompareTo(DirectCast(obj, Publisher).name)
	End Function

	#End Region

End Class

The modified class is having additional method from previous code.
C# Code

public int CompareTo(object obj)
    {
        if (this.GetType() != obj.GetType())
        {
            throw new ApplicationException("The object are not same type");
        }
        return this.name.CompareTo(((Publisher)obj).name);
    }

The CompareTo method is compare current object name attribute and other remaining objects attributes and return integer value based on result.

Step 4

Now do step 2 again and call Sort() method for ArrayList object.

C# Code

ArrayList collectionOfPub = new ArrayList();
            collectionOfPub.Add(new Publisher("Wrox", "No-02,John Ave 2", "US", "WROX"));
            collectionOfPub.Add(new Publisher("Apress", "No-03,Cels Ave 6", "US", "APRESS"));
            collectionOfPub.Add(new Publisher("Sams", "No-89,Test Ave 32", "US", "SAMS"));
            collectionOfPub.Add(new Publisher("Orelly", "No-23/08,John Ave 23", "US", "ORELLY"));
            collectionOfPub.Add(new Publisher("Packtpub", "No-56,John Ave 5", "INDIA", "PACKTPUB"));
            collectionOfPub.Sort();
            foreach (Publisher item in collectionOfPub)
            {
                Console.WriteLine("{0}:{1}", "Name", item.Name);
            }

VB.NET Code

Dim collectionOfPub As New ArrayList()
collectionOfPub.Add(New Publisher("Wrox", "No-02,John Ave 2", "US", "WROX"))
collectionOfPub.Add(New Publisher("Apress", "No-03,Cels Ave 6", "US", "APRESS"))
collectionOfPub.Add(New Publisher("Sams", "No-89,Test Ave 32", "US", "SAMS"))
collectionOfPub.Add(New Publisher("Orelly", "No-23/08,John Ave 23", "US", "ORELLY"))
collectionOfPub.Add(New Publisher("Packtpub", "No-56,John Ave 5", "INDIA", "PACKTPUB"))
collectionOfPub.Sort()
For Each item As Publisher In collectionOfPub
	Console.WriteLine("{0}:{1}", "Name", item.Name)
Next

When you call Sort() method for Arraylist, .NET Framework call CompareTo method each objects within the collection and compare and do the sorting internally.
Now run application and see the output.

Output 

Image Loading

Download Sample Project

Download source files -3 kb

References

  1. http://www.codegain.com/articles/csharp/miscellaneous/how-to-sort-a-generic-list-in-csharp.aspx

Conclusion

In this article, I will explain how to sort Arraylist with custom object. Sometimes you may add custom objects within the ArrayList and need to sort using an attribute in custom object. Hopes help and thank you for reading.

 
Sign Up to vote for this article
 
About Author
 
RRaveen
Occupation-Software Engineer
Company-TGS
Member Type-Gold
Location-Singapore
Joined date-03 Jun 2009
Home Page-codegain.com
Blog Page-www.codegain.com
- B.Sc. degree in Computer Science. - 4+ years experience in Visual C#.net and VB.net - Obsessed in OOP style design and programming. - Designing and developing Network security tools. - Designing and developing a client/server application for sharing files among users in a way other than FTP protocol. - Designing and implementing GSM gateway applications and bulk messaging. - Windows Mobile and Symbian Programming - Having knowledge with ERP solutions
 
 
Other popularSectionarticles
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top
</