C# - how to sort a Collection<T>?

Hi All

I have a generic Collection<T> 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:

    public class LibraryItemCollection: Collection<LibraryItem>
    {

    }

This is my item class:

    public class LibraryItem : IEqualityComparer<LibraryItem>, IComparable<LibraryItem>
    {

        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<T> 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

:slight_smile:

It’s pretty much all taken care of–implement IComparable and call Sort() on the collection and life is good. You might need to back the item with List<T> rather than Collection<T> as List definitely has a concept of order that collection might not.