Home > Software design >  What is the correct way to perform this sort operation?
What is the correct way to perform this sort operation?

Time:02-25

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...

CodePudding user response:

Your current Sorted method is unnecessary, but its logic can be used in the Bars class.

public class Bars
{
    public Foo Foo { get; set; }

    public static IEnumerable<Bar> Sorted(IEnumerable<Bar> bars)
    {
        return bars.OrderBy(b => b.Foo?.Left).ThenBy(b => b.Foo?.Right);
    }
}

CodePudding user response:

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());
    }
}
  • Related