2014-04-15 24 views
0

我想排序我的列表,其中T是產品。 該列表可能包含重複的元素ReportSeqId。我想根據ReportSeqId進行分類。排序列表<T>使用C#整數屬性

但是標準是,如果ReportSeqId = 0那麼它應該最後。

輸入:

new ilistProd<Products>() 
{ 
    new Products(0, Report1, SSR), 
    new Products(2, Report2, SBO), 
    new Products(0, Report3, PST), 
    new Products(3, Report4, ABR), 
    new Products(1, Report5, OSS), 
    new Products(0, Report6, TCP), 
} 

OUTPUT:

new ilistProd<Products>() 
{ 
    new Products(1, Report5, OSS), 
    new Products(2, Report2, SBO), 
    new Products(3, Report4, ABR), 
    new Products(0, Report3, PST), 
    new Products(0, Report6, TCP), 
    new Products(0, Report1, SSR) 
} 

下面是我的代碼:

public class Products 
{ 
    //ctor 
    public SDVar(int xiReportSeqId, string xiReportName, string xiProduct) 
    { 
     this.ReportSeqId = xiReportSeqId; 
     this.ReportName = xiReportName; 
     this.Product = xiProduct; 
    } 

    public int ReportSeqId {get; set;} 
    public string ReportName {get; set;} 
    public string Product {get; set;} 
} 


public class SDVar 
{ 
    //ctor 
public SDVar() 
{ 
} 

public void DoSort(ref List<Products> ilistProd) 
{ 
    ilistProd.Sort(delegate(Products x, Products y) 
    { 
     if (x.ReportSeqId == 0) 
     { 
      if (y.ReportSeqId == 0) 
      { 
       return 0; 
      } 
      return -1; 
     } 
     return x.ReportSeqId.CompareTo(y.ReportSeqId); 
    }  
} 
} 
+0

你嘗試換'-1'用'1'? (側面問題:爲什麼'參考列表'?在任何情況下,您都不會將輸入變量替換爲新列表) –

+0

實際代碼在排序後需要很多工作。這只是爲了舉一個例子。你可以考慮返回ilistProd。 –

回答

1

試試這個

list.Sort(delegate(Products x, Products y) 
{ 
    if(x.ReportSeqId == 0) 
     return 1;  
    if(y.ReportSeqId == 0) 
     return -1; 
    return x.ReportSeqId.CompareTo(y.ReportSeqId); 
}); 
0

使用LINQ

products = products.OrderBy(p => p.ReportSeqId == 0 ? Int32.MaxValue : p.ReportSeqId).ToList(); 
+0

對不起,添加一件事。我使用.Net Framework 2.0,所以LINQ可能不是我的選擇。 –

1

通常,我的首選解決方案是添加一個額外的屬性(例如, SortIndex),它可以在Linq中使用,也可以在一個排序委託中使用(其中id 0將返回一個int.maxvalue),但爲了使現有代碼正常工作,應該額外檢查第二個id是否爲0如果第一個ID是不是:

if (x.ReportSeqId == 0) 
{ 
    if (y.ReportSeqId == 0) 
    { 
     return 0; 
    } 
    return 1; 
} 
else if (y.ReportSeqId == 0) 
    return -1; 
return x.ReportSeqId.CompareTo(y.ReportSeqId); 
1

另一種方式是實現IComparable

public class Product : IComparable<Product> 
{ 
    private int ReportSeqId = 0; 

    public int CompareTo(Product other) 
    { 
     if (ReportSeqId == 0 || other == null) return 1; 

     if (other.ReportSeqId == 0) return - 1; 

     return ReportSeqId - other.ReportSeqId; 
    } 
}