2011-11-30 61 views
1

所以我有以下struct如何实现我的特别定制的的CompareTo

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()Foo[]的优势。

如何将逻辑(从我的特殊/有线OrderBy/ThenBy)转换为int CompareTo(Foo foo)

回答

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); 
    } 
} 
+1

(美孚等)不能为null - 这是一个结构,所以没必要来测试它。 –

+0

我想到的另外...另外,我只是好奇,如果我可以以某种方式增强'&'或者... ... –

+0

@RussellTroywest,正确,纠正。当我写这篇文章的时候,我已经有了上课的念头。 –

相关问题