I need to use a custom sorting algorithm on a WPF DataGrid's ListCollectionView.
I created an implementation of IComparer<string>
since I use strings but the CustomSort
property of ListCollectionView
only takes non-generic IComparer
implementation:
listCollectionView.CustomSort = new MyComparer(); // this wont work
Since my comparing logic is specifically for strings while I need an IComparer
instance, I was thinking about creating a MyComparerAdapter
adapter like so:
public class MyComparerAdapter : IComparer
{
private readonly IComparer<string> _innerComparer = new MyComparer();
public int Compare(object a, object b)
{
return _innerComparer.Compare((string)a, (string)b);
}
}
But I might as well implement the non-generic IComparer interface in the MyComparer
class which would call the generic Compare method.
Which solution would be more preferable and why? Would the adapter be a useless extra component in this? Is there a downside of implementing both the generic and the non-generic methods of IComparer?
CodePudding user response:
I find less is more. Implementing the bare minimum and adding only when it's needed.
Translated to your case, it depends...
Do you see yourself using the generic variant anywhere (in your view models)?
No
The CollectionView is object based by nature. Implementing just IComparer will suffice.
Yes
Implement both on MyComparer
. I've only used the Adapter / Decorator pattern when some pre- or postprocessing needed to be done.