Skip to content

GroupingProjection fails if groupkey does not implement IComparable #4

@sfmskywalker

Description

@sfmskywalker

The following code will fail with a System.ArgumentException: At least one object must implement IComparable. if:

  1. TGroupKey is not comparable
  2. No Group comparer is specified.
var projection =
                    mSourceCollection.ToArray()
                        .Where(mFilterPredicate)
                        .OrderBy(mOrderKeySelector, mOrderKeyComparer)
                        .GroupBy(mGroupKeySelector)
                        .Select(group => new Group(group.Key, group))
                        .OrderBy(x => x.Key, mGroupKeyComparer)
                        .ToArray();

Specifically, this line:

.OrderBy(x => x.Key, mGroupKeyComparer)

Either the key must implement IComparable, or a group key comparer must be specified.
If no group key comparer is specified, then the OrderBy should simply not happen. The following code fixes this issue:

var projectionQuery =
                    mSourceCollection.ToArray()
                        .Where(mFilterPredicate)
                        .OrderBy(mOrderKeySelector, mOrderKeyComparer)
                        .GroupBy(mGroupKeySelector)
                        .Select(group => new Group(group.Key, group));

                if (mGroupKeyComparer != null)
                    projectionQuery = projectionQuery.OrderBy(x => x.Key, mGroupKeyComparer);

                var projection = projectionQuery.ToArray();

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions