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:57

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...

查看更多
祖国的老花朵
3楼-- · 2020-05-24 20:00

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.

查看更多
登录 后发表回答