Solved

Sorting a custom collection using generics

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

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

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

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 …
A quick way to get a menu to work on our website, is using the Menu control and assign it to a web.sitemap using SiteMapDataSource. Example of web.sitemap file: (CODE) Sample code to add to the page menu: (CODE) Running the application, we wi…
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 …
Along with being a a promotional video for my three-day Annielytics Dashboard Seminor, this Micro Tutorial is an intro to Google Analytics API data.

806 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