Solved

Sorting a custom collection using generics

Posted on 2011-02-16
3
1,010 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 74

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

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Suggested Solutions

Today is the age of broadband.  More and more people are going this route determined to experience the web and it’s multitude of services as quickly and painlessly as possible. Coupled with the move to broadband, people are experiencing the web via …
User art_snob (http://www.experts-exchange.com/M_6114203.html) encountered strange behavior of Android Web browser on his Mobile Web site. It took a while to find the true cause. It happens so, that the Android Web browser (at least up to OS ver. 2.…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …

757 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

22 Experts available now in Live!

Get 1:1 Help Now