我有這堂課:
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);
}
}
現在給出一個類:
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>類來執行專案粒度比較來獲得純 LINQ 陳述句,但是給定的foos.OrderBy...LINQ 運算式已經是預期的結果......
uj5u.com熱心網友回復:
您當前的Sorted方法是不必要的,但它的邏輯可以在Bars類中使用。
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);
}
}
uj5u.com熱心網友回復:
您可以定義一個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());
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/434889.html
上一篇:帶有各種鍵的VB.NETLINQWHERE查詢集合拋出KeyNotFoundException
下一篇:將LINQ查詢轉換為SQL
