所以我跟随struct
public struct Foo
{
public readonly int FirstLevel;
public readonly int SecondLevel;
public readonly int ThirdLevel;
public readonly int FourthLevel;
}
某处我做了以下
var sequence = new Foo[0];
var orderedSequence = sequence
.OrderBy(foo => foo.FirstLevel)
.ThenBy(foo => foo.SecondLevel)
.ThenBy(foo => foo.ThirdLevel)
.ThenBy(foo => foo.FourthLevel);
现在我想实施System.IComparable<Foo>
以取得例如。 .Sort()
的{{1}}的优势。
如何将逻辑(从我的特殊/有线Foo[]
/ OrderBy
)转移到ThenBy
?
答案 0 :(得分:5)
如下:
public struct Foo : IComparable<Foo>
{
public readonly int FirstLevel;
public readonly int SecondLevel;
public readonly int ThirdLevel;
public readonly int FourthLevel;
public int CompareTo(Foo other)
{
int result;
if ((result = this.FirstLevel.CompareTo(other.FirstLevel)) != 0)
return result;
else if ((result = this.SecondLevel.CompareTo(other.SecondLevel)) != 0)
return result;
else if ((result = this.ThirdLevel.CompareTo(other.ThirdLevel)) != 0)
return result;
else
return this.FourthLevel.CompareTo(other.FourthLevel);
}
}