Anonymous IComparer implementation

前端 未结 8 955
一整个雨季
一整个雨季 2021-02-03 17:57

Is it possible to define an anonymous implementation of IComparer?

I believe Java allows anonymous classes to be defined inline - does C#?

Looking at this code I

相关标签:
8条回答
  • 2021-02-03 18:05

    C# does not allow implementing interfaces using anonymous inner classes inline, unlike Java. For simple comparisons (i.e. comparing on a single key), there is a better way to do this in C#. You can simply use the .OrderBy() method and pass in a lambda expression specifying the key.

    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;
    
    
    namespace Test{
        public class Test{
            public static void Main(){
                IList<int> mylist = new List<int>();
                for(int i=0; i<10; i++) mylist.Add(i);
                var sorted = mylist.OrderBy( x => -x );
                foreach(int x in sorted)
                    Console.WriteLine(x);
            }
        }
    }
    
    0 讨论(0)
  • 2021-02-03 18:12

    Even though you can't create anonymous classes that implement interfaces, you can usually use the Comparison Delegate instead of the IComparer Interface in most cases (like sorting, etc.):

    Array.Sort(arr, (x, y) => 1);
    

    Also there are some built-in implementations of IComparer like the Comparer Class or the StringComparer Class...

    0 讨论(0)
  • 2021-02-03 18:13

    Take a look at these 2 SO questions, they tackle essentially the same problem

    Use of Distinct with list of Custom Object

    Wrap a delegate in an IEqualityComparer

    If you go this way, you should pay special attention to Slaks' comments and Dan Tao's answer about the hashcode implementation

    0 讨论(0)
  • 2021-02-03 18:14

    No, C# does not currently allow inline interface implementations; although it does allow you to create delegates inline through lambda expressions and anonymous methods.

    In your case, I would suggest using a ProjectionComparer that makes it easy to use this feature, such as the one listed here.

    0 讨论(0)
  • Array.Sort(arrayName, (x,y) => string.Compare(x.Name,y.Name,StringComparison.CurrentCulture));
    
    0 讨论(0)
  • 2021-02-03 18:19

    No, this is not possible. However, you can get the default implementation of IComparer<TKey> by Comparer<TKey>.Default. Otherwise you'll need to create a parameterized implementation and use an instance of that.

    0 讨论(0)
提交回复
热议问题