2013-01-23 40 views
0

全部,查找下一個/ previos項目並設置爲當前項目

我有一個綁定到某個列表。

比方說,我有一個當前的指數。現在,我從列表中刪除幾個項目(可能彼此相鄰,也可能不相鄰)。如果我想將當前索引重置爲刪除後的下一個項目(或者如果沒有下一個項目,那麼最後一個項目,假設還有剩下的項目),那麼最好的方法是什麼也沒有做到這一點很多枚舉。

基本上,我堅持的是我似乎需要在執行刪除操作並在某處引用新對象之前弄清楚這一點,但似乎無法通過列舉幾個列表並引發我的困擾應用。

List<Object> MyCoolList; 
List<Object> ItemsIWillBeDeleting; 
Object CurrentItem; 

//For simplicity, assume all of these are set and known for the following code 
int i = MyCoolList.IndexOf(CurrentItem); 
Object NewCurrentItem = null; 
if (MyCoolList.Any(a => MyCoolList.IndexOf(a) > i && !ItemsIWillBeDeleting.Any(b => b==a))) 
{ 
    NewCurrentItem = MyCoolList.First(a => MyCoolList.IndexOf(a) > i && !ItemsIWillBeDeleting.Any(b => b==a)); 
    ItemsIWillBeDeleting.ForEach(a => MyCoolList.Remove(a)); 
    CurrentItem = NewCurrentItem; 
} 
else (if MyCoolList.Count > MyCoolList.Count) 
{ 
    NewCurrentItem = MyCoolList.Last(a => !ItemsIWillBeDeleting.Any(b => b==a)) 
    ItemsIWillBeDeleting.ForEach(a => MyCoolList.Remove(a)); 
    CurrentItem = MyCoolList.Last(); 
} 
else 
{ 
    MyCoolList.Clear(); //Everything is in MyCoolList is also in ItemsIWillBeDeleting 
    CurrentItem = null; 
} 

我確信有更好的方式來與Linq做到這一點,但我努力尋找它。有任何想法嗎?

謝謝。

+0

Linq和Indices不是朋友。 –

+0

好的。我想我明白了。我只使用Enumerator和NextItem(或者其他所謂的)。 – William

回答

0
private ICollection<MyCoolClass> _someCollection 

public void DeleteAndSetNext(IEnumerable<MyCoolClass> IEDelete) 
{ 
    bool boolStop = false; 
    MyCoolClass NewCurrent = _someCollection.FirstOrDefault(a => 
     { 
      if (!boolStop) boolStop = IEDelete.Contains(a); 
      return boolStop && !IEDelete.Contains(a); 
     }); 
    foreach (MyCoolClass cl in IEDelete) 
    { 
     _someCollection.Remove(a); 
    } 
    CurrentMyCoolClass = NewCurrent ?? _someCollection.LastOrDefault(); 
} 

MyCoolClass CurrentMyCoolClass 
{ 
    get; 
    set; 
} 
相關問題