2012-07-31 22 views
1

我有對象爲負面列表排序在中間

public class foo 
{ 
    public decimal val1 {get;set;} 
    public decimal val2 {get;set;} 
} 

val1val2可以同時包含陰性或陽性值的列表。 如果我有一個List<foo>items有沒有一種乾淨的方法,我可以對它們進行排序,使得val1或val2中的負值不是列表中的第一項或最後一項。

我的列表大小可以從1 - 100非常小。如果小於3,我不需要排序。但如果它是>= 3我需要確保任何負值不是列表中的第一個或最後一個。

+0

這可能嗎?他們可能都是消極的。 – zmbq 2012-07-31 05:20:39

+0

我也很好奇,你能用更具描述性的例子來詳細說明嗎? – jamesbar2 2012-07-31 05:21:33

+0

如果他們都是積極的或所有消極的,那麼訂單並不重要 – Daveo 2012-07-31 05:22:52

回答

1

你會試圖推動「正」值的頭和表尾,如果它們存在:

if (myList.Count > 2) 
{ 
    //push a positive to the head of the list 
    var firstPositive = myList.FirstOrDefault(x => x.val1 > 0 && x.val2 > 0); 
    if (firstPositive != null) 
    { 
     myList.Remove(firstPositive); 
     myList.Insert(0, firstPositive); 
    } 

    //push a positive to the tail of the list 
    var secondPositive = myList.Skip(1).FirstOrDefault(x => x.val1 > 0 && x.val2 > 0); 
    if (secondPositive != null) 
    { 
     myList.Remove(secondPositive); 
     myList.Add(secondPositive); 
    } 
} 
+0

感謝更多的可讀性,然後我想到的解決方案=) – Daveo 2012-07-31 05:47:50

1

創建您自己的MyList:List<decimal>類並覆蓋Add(..),Insert(...),Remove(..)和其他方法以滿足您的需求。

或者您可以使用ObservableCollectiondecimal並收聽CollectionChanged事件。