c# - IComparer classes for custom class -
i have bunch cards in list, , want sort them ascending or descending:
private list<card> cards = new list<card>();
ascending/descending mean have compare values of cards, simply.
what do? icomparable interface seems not enough because can sort 1 "default" way. trying implement icomparer
, fail. in same class file card, try add comparing class descending order:
public class cardcompdesc : icomparer<card> { int icomparer.compare(object a, object b) // return 0, -1, or -1 later return 0 { }
but here compiler complains cannot find icomparer in current context. if remove <card>
definition, class compiles. in order able sort cards above, this: this.cards.sort(new cardcompdesc());
looks have use icomparer<> on icomparer. doing wrong?
i grabbed compare use works.. here gist of it...
using system; using system.collections.generic; using system.linq; using system.text; namespace mynamespace { public class mycomparer: icomparer<int> { public int compare(int x, int y) { // x greater move if (x > y) { return 1; } // x smaller move y if (x < y) { return -1; } // nothing (equal) return 0; } } }
Comments
Post a Comment