Search code examples
c#linqcomparetoicomparable

Get items in a list that are greater than a selected item


I have a list of Versions.

List<Version> versions = GetVersions();

And I have a selectedVersion.

My Version class implements IComparable.

public class Version : IComparable<Version>

So I can do versions.Sort(). At this point my Version objects are sorted in the list let's say by the Name property.

From the list of Versions, I would like to get items that are higher than my selectedVersion. How can I do that with Linq?

What I have tried is casting the selectedVersion to IComparable and then using CompareTo but I get an InvalidCastException error.

IComparable comparable = (IComparable)selectedVersion;
if(comparable.CompareTo(selectedVersion)) > 0

Solution

  • The correct way is to use Comparer<T>.Default which will work as soon as the type T implements either IComparable<T> or IComparable:

    var result = versions
        .Where(version => Comparer<Version>.Default.Compare(version, selectedVersion) > 0)
        .ToList();
    

    You can even encapsulate it in a custom extension method (so you DRY):

    public static class EnumerableExtensions
    {
        public static IEnumerable<T> GreaterThan<T>(this IEnumerable<T> source, T value, IComparer<T> comparer = null)
        {
            if (comparer == null) comparer = Comparer<T>.Default;
            return source.Where(item => comparer.Compare(item, value) > 0);
        }
    }
    

    and use simply

    var result = versions.GreaterThan(selectedVersion).ToList();