?
Solved

Sorting a custom collection using generics

Posted on 2011-02-16
3
Medium Priority
?
1,019 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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 2000 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

On Demand Webinar: Networking for the Cloud Era

Ready to improve network connectivity? Watch this webinar to learn how SD-WANs and a one-click instant connect tool can boost provisions, deployment, and management of your cloud connection.

Question has a verified solution.

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

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 …
We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
Michael from AdRem Software explains how to view the most utilized and worst performing nodes in your network, by accessing the Top Charts view in NetCrunch network monitor (https://www.adremsoft.com/). Top Charts is a view in which you can set seve…
If you’ve ever visited a web page and noticed a cool font that you really liked the look of, but couldn’t figure out which font it was so that you could use it for your own work, then this video is for you! In this Micro Tutorial, you'll learn yo…

752 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