'What is the correct way to perform this sort operation?

I have this class:

public class Foo
{
    public int Left {get;set}
    public int Right {get;set;}

    public static IEnumerable<Foo> Sorted(IEnumerable<Foo> foos)
    {
        return foos.OrderBy(x=>x.Left).ThenBy(x=>x.Right);
    }
}

Now given a class:

public class Bar
{
    public Foo Foo {get;}

    public IEnumerable<Bar> Sorted(IEnumerable<Bar> bars)
    {
        //Sort the bars by this logic: the order of bars is equivalent to the order of their Foos when sorted by Foo.Sorted().
    }
}

I'm not sure what to put in my method to perform the correct sort.

Edit: I am also aware that a pure LINQ statement might be had by crafting a IComparer<T> class to perform a item-granular comparison, but the given foos.OrderBy... LINQ expression is already the intended outcome...



Solution 1:[1]

You could define an IComparer<Foo> and use that:

public class FooComparer : IComparer<Foo>
{
    public int Compare(Foo? x, Foo? y)
    {
        if (x.Left == y.Left) x.Right.CompareTo(y.Right);
        return x.Left.CompareTo(y.Left);
    }
}

public class Foo
{
    public int Left { get; set; }
    public int Right { get; set; }

    public IEnumerable<Foo> Sorted(IEnumerable<Foo> foos)
    {
        return foos.OrderBy(x => x, new FooComparer());
    }
}

public class Bar
{
    public Foo Foo {get;}

    public IEnumerable<Bar> Sorted(IEnumerable<Bar> bars)
    {
        return bars.OrderBy(x => x.Foo, new FooComparer());
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1