1

I'm working on a primitive quicksort algorithm using LINQ and generics but I've run into some issues, mainly with type inference.

Here is the code

private static List<T> Quicksort<T>(IEnumerable<T> list) 
            where T : IComparable, IComparable<T>
        {
            if (!list.Any()) 
                return new List<T>();

            var first = list.First();
            var smallerAndLarger = list.Skip(1).GroupBy(n => n >= first);

            return new List<T>
                (Quicksort(smallerAndLarger.Where(x => !x.Key)).Add(first))
                .AddRange(Quicksort(smallerAndLarger.Where(x => x.Key)));
        }

The compiler is complaining about this line

var smallerAndLarger = list.Skip(1).GroupBy(n => n >= first);

Saying that the type T will not support comparison operations, but I have already set in the method signature that T should implement IComparable and the generic version so this should work?

Overly Excessive
  • 2,095
  • 16
  • 31
  • 5
    When you use GroupBy, do you mean to use Where? – Rob G Nov 12 '14 at 19:22
  • 3
    Use the `IComparable` interface: don't use the `>=` operator but the `CompareTo` method. Or take a `IComparer` as a parameter: [see here for details](http://stackoverflow.com/a/26202958/3764814) - `IComparer` is similar to the `IEqualityComparer` interface discussed in that answer, just use `Comparer.Default` as a default comparer value. – Lucas Trzesniewski Nov 12 '14 at 19:23

1 Answers1

4

The problem is your use of >= (ie: n=> n >= first) which is not available unless a type defines how to use the operator (IComparable doesn't).

Instead of using the gt/lt/eq operators, use CompareTo (http://msdn.microsoft.com/en-us/library/system.icomparable.compareto(v=vs.110).aspx) in order to determine precedence:

n => n.CompareTo(first) >= 0
dshapiro
  • 376
  • 2
  • 12