Advantages/Disadvantages of different implementations for Comparing Objects

后端 未结 5 632
滥情空心
滥情空心 2021-02-05 09:27

This questions involves 2 different implementations of essentially the same code.

First, using delegate to create a Comparison method that can be used as a parameter whe

5条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-05 10:12

    In your case, advantage of having an IComparer over Comparision delegate, is that you can also use it for the Sort method, so you don't need a Comparison delegate version at all.

    Another useful thing you can do is implementing a delegated IComparer implementation like this:

    public class DelegatedComparer : IComparer
    {
      Func _comparision;
      public DelegatedComparer(Func comparision)
      {
        _comparision = comparision;
      }
      public int Compare(T a,T b) { return _comparision(a,b); }
    }
    
    list.Sort(new DelegatedComparer((foo1,foo2)=>foo1.Bar.CompareTo(foo2.Bar));
    

    and a more advanced version:

    public class PropertyDelegatorComparer : DelegatedComparer
    {
      PropertyDelegatorComparer(Func projection)
        : base((a,b)=>projection(a).CompareTo(projection(b)))
    }
    

提交回复
热议问题