2017-02-02 61 views
0

我有一個從組中刪除用戶的功能。錯誤的信息,因爲for循環

首先它檢查組中是否有用戶。然後在for循環中,它會遍歷所有用戶,並檢查組中是否存在當前輸入的用戶。

第一次工作。它刪除用戶。但在第二次用戶不再存在,它涉及到else語句。

如何在用戶被刪除時結束for循環?

下面是代碼:

for (int y = 0; y < cognosGroup.members.value.Length; y++) 
{ 
    //check if member[y] is the one that need to be deleted 
    if (cognosGroup.members.value[y].searchPath.value == member[0].searchPath.value) 
    { 
     int lenght = cognosGroup.members.value.Length - 1; 

     baseClass[] newMembers = new baseClass[lenght]; 
     int index = 0; 
     baseClass obj = null; 
     // go trough group 
     for (int i = 0; i <= lenght; i++) 
     { 
      if (i != y) 
      { 
       //create user 
       obj = cognosGroup.members.value[i]; 
       newMembers[index] = obj; 
       index++; 
      } 
      else 
      { 
       this._messageText = "*Succesfully removed " + this.RemoveUsername.ToLower() + " from " + this.DataViewModel.GroupModel.SelectedGroup; 
       this.ExHandling = new ExceptionHandling(this._messageText); 
       this.MessageText = this.ExHandling.ExHandlingOkey; 
      } 
     } 
     cognosGroup.members = new baseClassArrayProp(); 
     cognosGroup.members.value = newMembers; 
     this.LogonModel.CBICMS.update(new baseClass[] { cognosGroup }, new updateOptions()); 
     y--; 
    } 
    else 
    { 
     this._messageText = "*" + this.RemoveUsername.ToLower() + " is not a user from " + this.DataViewModel.GroupModel.SelectedGroup; 
     this.ExHandling = new ExceptionHandling(this._messageText); 
     this.MessageText = this.ExHandling.ExHandlingError; 
    } 
} 
+4

'break'聲明?順便說一下,這段代碼可以重寫成一行。請參閱:[如何從C#中的數組中刪除元素](http://stackoverflow.com/q/496896/69809)。 – Groo

+1

你可以使用break? –

+2

嚴重的是,不要這樣做,如果你可以這樣做:'members.value = members.value.Where(v => v.searchPath.value!= item).ToArray();'。 [*代碼就好像最終維護你的代碼的人是一個暴力的精神病患者,他知道你住在哪裏*](http://wiki.c2.com/?CodeForTheMaintainer)。 – Groo

回答

3

只需使用return語句退出程序或繼續跳到下一個迭代。

+0

哦,那麼容易。非常感謝你! – Purger86

+3

退出退出功能,中斷退出你所在的循環。 – Thor