[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
?
Solved

Sorting a custom collection using generics

Posted on 2011-02-16
3
Medium Priority
?
1,020 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

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

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

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…
IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
This tutorial will teach you the special effect of super speed similar to the fictional character Wally West aka "The Flash" After Shake : http://www.videocopilot.net/presets/after_shake/ All lightning effects with instructions : http://www.mediaf…
Are you ready to place your question in front of subject-matter experts for more timely responses? With the release of Priority Question, Premium Members, Team Accounts and Qualified Experts can now identify the emergent level of their issue, signal…
Suggested Courses

656 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