Reputation: 143
How can I implement IComparer
int CompareTo(object obj)
with an additional parameter, like
int CompareTo(object obj, Dictionary<int, int> preferences)
preferences is a dictionary with Id
and NumberOfClicks<int, int>
What I want is compare contents which have categoryId by the number of clicks in the dictionary,
Example Cat 1 has 3 clicks, Cat 2 has 6 clicks.
Sort by comparing
preferences[this.CategoryId].value > preferences[object.CategoryId].value
So they are sorted by category, but in relation to the Dictionary
.
Upvotes: 3
Views: 843
Reputation: 203820
Create a separate comparer class that implements IComparer<T>
, rather than having the type itself implement IComparable
, and have it accept the Dictionary
in its constructor. That comparer can then use the dictionary when it compares instances of your object.
Upvotes: 0
Reputation: 726569
You cannot pass extra arguments to IComparer
's Compare
method, because method signature must match the signature in the interface.
What you can do is to construct an instance of IComparer
with the extra parameter, store it in the instance, and use inside CompareTo
as needed:
class MyComparer : IComparer<object> {
private readonly IDictionary<int, int> preferences;
public MyComparer(IDictionary<int, int> preferences) {
this.preferences = preferences;
}
public int Compare(object a, object b) {
... // Perform the comparison with preferences in scope
}
}
Upvotes: 5