C# Sortable collection which allows duplicate keys

前端 未结 16 2163
旧巷少年郎
旧巷少年郎 2020-11-28 10:06

I am writing a program to set a sequence in which various objects will appear in report. The sequence is the Y position (cell) on Excel spreadsheet.

A demo part of co

16条回答
  •  青春惊慌失措
    2020-11-28 10:56

    Use your own IComparer!

    Like already stated in some other answers, you should use your own comparer class. For this sake I use a generic IComparer class, that works with anything that implements IComparable:

    /// 
    /// Comparer for comparing two keys, handling equality as beeing greater
    /// Use this Comparer e.g. with SortedLists or SortedDictionaries, that don't allow duplicate keys
    /// 
    /// 
    public class DuplicateKeyComparer
                    :
                 IComparer where TKey : IComparable
    {
        #region IComparer Members
    
        public int Compare(TKey x, TKey y)
        {
            int result = x.CompareTo(y);
    
            if (result == 0)
                return 1;   // Handle equality as beeing greater
            else
                return result;
        }
    
        #endregion
    }
    

    You will use it when instancing a new SortedList, SortedDictionary etc:

    SortedList slist = new SortedList(new DuplicateKeyComparer());
    

    Here int is the key that can be duplicate.

提交回复
热议问题