Solved

Sorting a custom collection using generics

Posted on 2011-02-16
3
1,011 Views
Last Modified: 2012-08-13
I have a class (attached) that should help me sorting customs (stongly typed) collections. The "Sort" is implemated in my collection like this:

    [Serializable()]
    public class UserCollection : CollectionBase, IEnumerable
    {
        public void Sort(IComparer Comparer)
        {
            ArrayList list = ArrayList.Adapter(base.List);
            list.Sort(0, list.Count, Comparer);
        }
    }


This is how I try to sort my user collection by users Lastname:

UserCollection.Sort(new Sort.GenericComparer<User>("LastName", Sort.GenericComparer<User>.SortOrder.Descending));


The only thing is that I get this error when trying to sort my collection:

Argument '1': cannot convert from 'Sort.GenericComparer<User>' to 'System.Collections.IComparer'


Can someone please tell me why I get this error message?
Thank you :)
/// <summary>
/// This class is used to compare any 
/// type(property) of a class for sorting.
/// This class automatically fetches the 
/// type of the property and compares.
/// </summary>

public sealed class GenericComparer<T> : IComparer<T>
{
    public enum SortOrder { Ascending, Descending };

    #region member variables
    private string sortColumn;
    private SortOrder sortingOrder;
    #endregion


    #region constructor
    public GenericComparer(string sortColumn, SortOrder sortingOrder)
    {
        this.sortColumn = sortColumn;
        this.sortingOrder = sortingOrder;
    }
    #endregion


    #region public property
    /// <summary>
    /// Column Name(public property of the class) to be sorted.
    /// </summary>
    public string SortColumn
    {
        get { return sortColumn; }
    }

    /// <summary>
    /// Sorting order.
    /// </summary>
    public SortOrder SortingOrder
    {
        get { return sortingOrder; }
    }
    #endregion
    

    #region public methods
    /// <summary>
    /// Compare interface implementation
    /// </summary>
    /// <param name="x">custom Object</param>
    /// <param name="y">custom Object</param>
    /// <returns>int</returns>

    public int Compare(T x, T y)
    {
        PropertyInfo propertyInfo = typeof(T).GetProperty(sortColumn);
        IComparable obj1 = (IComparable)propertyInfo.GetValue(x, null);
        IComparable obj2 = (IComparable)propertyInfo.GetValue(y, null);

        if (sortingOrder == SortOrder.Ascending)
        {
            return (obj1.CompareTo(obj2));
        }
        else
        {
            return (obj2.CompareTo(obj1));
        }
    }

    #endregion
}

Open in new window

0
Comment
Question by:webressurs
3 Comments
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 34911096
Where is the definition for the Sort class as found in:

    UserCollection.Sort(new Sort.GenericComparer<User>("LastName", Sort.GenericComparer<User>.SortOrder.Descending));
0
 
LVL 1

Author Comment

by:webressurs
ID: 34913760
It is the attached cide snippet :)
0
 
LVL 2

Accepted Solution

by:
chTeja earned 500 total points
ID: 34915816
Implement IComparer in the class GenericComparer. That should fix this. Sample code provided below.

class GenericComparer<T> : IComparer, IComparer<T> where T : class
    {
        #region IComparer<T> Members

        public int Compare(T x, T y)
        {
            Console.WriteLine("In");
            if (x != null && y != null)
            {
                int result = 0;
                // Actual Comparison done and result assigned here.
                return result;
            }
            else
            {
                throw new InvalidOperationException("Invalid input values detected.");
            }
        }

        #endregion

        #region IComparer Members

        public int Compare(object x, object y)
        {
            return this.Compare(x as T, y as T);
        }

        #endregion
    }

Open in new window

0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
This tutorial gives a high-level tour of the interface of Marketo (a marketing automation tool to help businesses track and engage prospective customers and drive them to purchase). You will see the main areas including Marketing Activities, Design …
Both in life and business – not all partnerships are created equal. As the demand for cloud services increases, so do the number of self-proclaimed cloud partners. Asking the right questions up front in the partnership, will enable both parties …

910 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

25 Experts available now in Live!

Get 1:1 Help Now