Anonymous IComparer implementation

2020-05-24 19:31发布

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 want to define a custom IComparer inline

public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(
    this IEnumerable<TSource> source,
    Func<TSource, TKey> keySelector,
    IComparer<TKey> comparer
)

标签: c#
8条回答
老娘就宠你
2楼-- · 2020-05-24 19:43

The .NET framework version 4.5 provides the method Comparer.Create(Comparison) to create comparers based on a specified comparison delegate (which can be a lambda function). However people who are working with earlier versions of .NET will probably need to implement something similar themselves.

查看更多
冷血范
3楼-- · 2020-05-24 19:45

Array.Sort(arrayName, (x,y) => string.Compare(x.Name,y.Name,StringComparison.CurrentCulture));

查看更多
迷人小祖宗
4楼-- · 2020-05-24 19:47

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.

查看更多
We Are One
5楼-- · 2020-05-24 19:47

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);
        }
    }
}
查看更多
放我归山
6楼-- · 2020-05-24 19:48

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

查看更多
ら.Afraid
7楼-- · 2020-05-24 19:49

As indicated in one of the comments below, .Net 4.5 allows this via a static method on the Comparer<> class, e.g. comparing two objects based on the value of a property in the class:

var comparer = Comparer<KilowattSnapshot>.Create( 
        (k1, k2) => k1.Kilowatt.CompareTo(k2.Kilowatt) );

Obviously this can be used inline rather than assigned to a variable.

查看更多
登录 后发表回答