开发者

How do I implement a LINQ-type IComparer<T> overload where T implements IComparable<T>?

开发者 https://www.devze.com 2023-04-12 03:23 出处:网络
I am implementing a class that in the style of the LINQ libraries has an overload for a custom IComparer. (e.g. OrderBy: OrderBy<TSource, TKey>(IEnumerable<TSource>, Func<TSource, TKey&

I am implementing a class that in the style of the LINQ libraries has an overload for a custom IComparer. (e.g. OrderBy: OrderBy<TSource, TKey>(IEnumerable<TSource>, Func<TSource, TKey>) and OrderBy<TSource, TKey>(IEnumerable<TSource>, Func<TSource, TKey>, IComparer<TKey>)).

I would like to implement 开发者_如何学Cthe 2-argument overload in terms of the 1-argument overload. Something like the following:

T Method<T>(IEnumerable<T> collection, IComparer<T> comparer)
{
    // Do something that returns a T
}

T Method<T>(IEnumerable<T> collection) where T: IComparable<T>
{
    IComparer<T> comparer = /*what goes here?*/;
    return Method(collection, comparer);
}

In this respect, the question boils down to asking, how do I obtain an instance of IComparer for a type that implements IComparable?


You are looking for Comparer<T>.Default.

0

精彩评论

暂无评论...
验证码 换一张
取 消