c# - How do I implement IComparable<T>? -


i've created own generic java data structure library, i'm creating in c#, i'm stuck trying implement compareto method sort singly linked list. here's code:

class sortedsinglylinkedlist<t> : icomparable // class // [irrelevant stuff...] // sorts list, least greatest element     public void sort()     {         (int = 0; < count; i++)         {             (int j = 0; j < count; j++)             {                 if (get(i).compareto(get(j)) < 0) // error -> 't' not contain definition 'compareto' , no extension method 'compareto' accepting first argument of type't' found (are missing using directive or assembly reference?)                 {                     move(i, j); // method moves node j                 }             }         }     }      // compares 2 elements     int icomparable<t>.compareto(t other)     {         // should put here make work?     } 

one way of achieving this, require elements of list comparable, i.e. have them implement icomparable interface. express using generic type constraint on t, in:

public class sortedsinglylinkedlist<t> : t : icomparable  

a more general way of doing this, allows list contain elements not implement icomparable interface, follow strategy used in many of c# bcl generic collection classes (e.g. sorteddictionary or sortedlist): use icomparer instance perform comparisons.

public class sortedsinglylinkedlist<t> {     private readonly icomparer<t> _comparer;      // ...      public sortedsinglylinkedlist()     {         _comparer = comparer<t>.default; // use default.         // ...     }      public sortedsinglylinkedlist(icomparer<t> comparer)     {         _comparer = comparer ?? comparer<t>.default;         // ...     } } 

and in sort method, use comparer instance perform comparisons:

_comparer.compare(get(i), get(j)); 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -