执行此排序操作的正确方法是什么?
What is the correct way to perform this sort operation?
我有这个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);
}
}
现在给出一个 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().
}
}
我不确定要在我的方法中放入什么来执行正确的排序。
编辑:我也知道可以通过制作 IComparer<T>
class 来执行项目粒度比较来获得纯 LINQ 语句,但是给定的 foos.OrderBy...
LINQ 表达式已经是预期的结果...
您当前的Sorted
方法是不必要的,但其逻辑可以用于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);
}
}
您可以定义一个 IComparer<Foo>
并使用它:
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());
}
}
我有这个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);
}
}
现在给出一个 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().
}
}
我不确定要在我的方法中放入什么来执行正确的排序。
编辑:我也知道可以通过制作 IComparer<T>
class 来执行项目粒度比较来获得纯 LINQ 语句,但是给定的 foos.OrderBy...
LINQ 表达式已经是预期的结果...
您当前的Sorted
方法是不必要的,但其逻辑可以用于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);
}
}
您可以定义一个 IComparer<Foo>
并使用它:
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());
}
}