Visual Studio Developer Center > Visual C# Forums > Visual C# General > how to sort a Collection<T> ???

Answered how to sort a Collection<T> ???

  • Sunday, May 25, 2008 1:26 PM
     
     

    Hi All

    I have a generic Collection and am trying to work out how I can sort the items contained within it. Ive tried a few things but I cant get any of them working.

     

    This is my collection class:

     

    Code Snippet

    public class LibraryItemCollection: Collection
        {

        }

     

     

     

    This is my item class:

     

    Code Snippet

    public class LibraryItem : IEqualityComparer, IComparable
        {

            private string _name;
            public string Name
            {
                get { return _name; }
                set { _name = value; }
            }

            #region IEqualityComparer Members

            internal CaseInsensitiveComparer comparer = CaseInsensitiveComparer.Default;

            public bool Equals(LibraryItem x, LibraryItem y)
            {
                if (comparer.Compare(x.Name, y.Name) == 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }

            public int GetHashCode(LibraryItem obj)
            {
                return obj.ToString().ToLower().GetHashCode();
            }

            #endregion

            #region IComparable members

            public int CompareTo(LibraryItem item)
            {
                return this.Name.CompareTo(item.Name);
            }

            #endregion
    }

     

     

     

    any help on how I can sort the  LibraryItemCollection class would be really appreciated...

    thanks

     

    Smile

     

Answers

  • Sunday, May 25, 2008 2:49 PM
     
     Answered

    Hi

     

    Thanks for the reply. I have seen that article, and while a nice solution, it doesnt work for me because he uses List<T> which has the Sort() method. I am using Collection<T> which doesnt have a sort method.. So creating a generic comparer is a bit pointless because I have no method to pass it to!

     

    *UPDATE*

     

    Have just worked out all I need to do is implement this method in my collection class:

     

    public LibraryItemCollection Sort()

    {

    List<LibraryItem> items = (List<LibraryItem>)Items;

    items.Sort();

    return this;

    }

     

    and I thought it was going to be something much more complex (as per the example)

     

    thanks for your help Smile

All Replies