C#在foreach遍歷刪除集合中元素的三種實(shí)現(xiàn)方法
前言
在foreach中刪除元素時(shí),每一次刪除都會(huì)導(dǎo)致集合的大小和元素索引值發(fā)生變化,從而導(dǎo)致在foreach中刪除元素時(shí)會(huì)拋出異常。
集合已修改;可能無(wú)法執(zhí)行枚舉操作。
方法一:采用for循環(huán),并且從尾到頭遍歷
如果從頭到尾正序遍歷刪除的話,有些符合刪除條件的元素會(huì)成為漏網(wǎng)之魚;
正序刪除舉例:
 List<string> tempList = new List<string>() { "a","b","b","c" };
 for (int i = 0; i < tempList.Count; i++)
 {
  if (tempList[i] == "b")
  {
   tempList.Remove(tempList[i]);
  }
 }
 tempList.ForEach(p => {
  Console.Write(p+",");
 });
控制臺(tái)輸出結(jié)果:a,b,b,c
有兩個(gè)2沒(méi)有刪除掉;
這是因?yàn)楫?dāng)i=1時(shí),滿足條件執(zhí)行刪除操作,會(huì)移除第一個(gè)b,接著第二個(gè)b會(huì)前移到第一個(gè)b的位置,即游標(biāo)1對(duì)應(yīng)的是第二個(gè)b。
接著遍歷i=2,也就跳過(guò)第二個(gè)b。
用for倒序遍歷刪除,從尾到頭
 List<string> tempList = new List<string>() { "a","b","b","c" };
 for (int i = tempList.Count-1; i>=0; i--)
 {
  if (tempList[i] == "b")
  {
   tempList.Remove(tempList[i]);
  }
 }
 tempList.ForEach(p => {
  Console.Write(p+",");
 });
控制臺(tái)輸出結(jié)果:a,c,
這次刪除了所有的b;
方法二:使用遞歸
使用遞歸,每次刪除以后都從新foreach,就不存在這個(gè)問(wèn)題了;
 static void Main(string[] args)
 {
  List<string> tempList = new List<string>() { "a","b","b","c" };
  RemoveTest(tempList);
  tempList.ForEach(p => {
   Console.Write(p+",");
  });
 }
 static void RemoveTest(List<string> list)
 {
  foreach (var item in list)
  {
   if (item == "b")
   {
    list.Remove(item);
    RemoveTest(list);
    return;
   }
  }
 }
控制臺(tái)輸出結(jié)果:a,c,
正確,但是每次都要封裝函數(shù),通用性不強(qiáng);
方法三:通過(guò)泛型類實(shí)現(xiàn)IEnumerator
 static void Main(string[] args)
 {
  RemoveClass<Group> tempList = new RemoveClass<Group>();
  tempList.Add(new Group() { id = 1,name="Group1" }) ;
  tempList.Add(new Group() { id = 2, name = "Group2" });
  tempList.Add(new Group() { id = 2, name = "Group2" });
  tempList.Add(new Group() { id = 3, name = "Group3" });
  foreach (Group item in tempList)
  {
   if (item.id==2)
   {
    tempList.Remove(item);
   }
  }
  foreach (Group item in tempList)
  {
   Console.Write(item.id+",");
  }
 //控制臺(tái)輸出結(jié)果:1,3
 public class RemoveClass<T>
 {
  RemoveClassCollection<T> collection = new RemoveClassCollection<T>();
  public IEnumerator GetEnumerator()
  {
   return collection;
  }
  public void Remove(T t)
  {
   collection.Remove(t);
  }
  public void Add(T t)
  {
   collection.Add(t);
  }
 }
 public class RemoveClassCollection<T> : IEnumerator
 {
  List<T> list = new List<T>();
  public object current = null;
  Random rd = new Random();
  public object Current
  {
   get { return current; }
  }
  int icout = 0;
  public bool MoveNext()
  {
   if (icout >= list.Count)
   {
    return false;
   }
   else
   {
    current = list[icout];
    icout++;
    return true;
   }
  }
  public void Reset()
  {
   icout = 0;
  }
  public void Add(T t)
  {
   list.Add(t);
  }
  public void Remove(T t)
  {
   if (list.Contains(t))
   {
    if (list.IndexOf(t) <= icout)
    {
     icout--;
    }
    list.Remove(t);
   }
  }
 }
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)我們的支持。
欄 目:C#教程
下一篇:C# List介紹及具體用法
本文標(biāo)題:C#在foreach遍歷刪除集合中元素的三種實(shí)現(xiàn)方法
本文地址:http://www.jygsgssxh.com/a1/C_jiaocheng/4586.html
您可能感興趣的文章
- 01-10C#實(shí)現(xiàn)將窗體固定在顯示器的左上角且不能移動(dòng)的方法
 - 01-10C#實(shí)現(xiàn)在Form里面內(nèi)嵌dos窗體的方法
 - 01-10C#中查找Dictionary中的重復(fù)值的方法
 - 01-10C#實(shí)現(xiàn)在啟動(dòng)目錄創(chuàng)建快捷方式的方法
 - 01-10關(guān)于nancy中的身份驗(yàn)證
 - 01-10C#編程自學(xué)之類和對(duì)象
 - 01-10C#遍歷文件夾后上傳文件夾中所有文件錯(cuò)誤案例分析
 - 01-10C#創(chuàng)建不規(guī)則窗體的4種方式詳解
 - 01-10C#實(shí)現(xiàn)讀取DataSet數(shù)據(jù)并顯示在ListView控件中的方法
 - 01-10C#中yield用法使用說(shuō)明
 


閱讀排行
- 1C語(yǔ)言 while語(yǔ)句的用法詳解
 - 2java 實(shí)現(xiàn)簡(jiǎn)單圣誕樹的示例代碼(圣誕
 - 3利用C語(yǔ)言實(shí)現(xiàn)“百馬百擔(dān)”問(wèn)題方法
 - 4C語(yǔ)言中計(jì)算正弦的相關(guān)函數(shù)總結(jié)
 - 5c語(yǔ)言計(jì)算三角形面積代碼
 - 6什么是 WSH(腳本宿主)的詳細(xì)解釋
 - 7C++ 中隨機(jī)函數(shù)random函數(shù)的使用方法
 - 8正則表達(dá)式匹配各種特殊字符
 - 9C語(yǔ)言十進(jìn)制轉(zhuǎn)二進(jìn)制代碼實(shí)例
 - 10C語(yǔ)言查找數(shù)組里數(shù)字重復(fù)次數(shù)的方法
 
本欄相關(guān)
- 01-10C#通過(guò)反射獲取當(dāng)前工程中所有窗體并
 - 01-10關(guān)于ASP網(wǎng)頁(yè)無(wú)法打開的解決方案
 - 01-10WinForm限制窗體不能移到屏幕外的方法
 - 01-10WinForm繪制圓角的方法
 - 01-10C#實(shí)現(xiàn)txt定位指定行完整實(shí)例
 - 01-10WinForm實(shí)現(xiàn)仿視頻播放器左下角滾動(dòng)新
 - 01-10C#停止線程的方法
 - 01-10C#實(shí)現(xiàn)清空回收站的方法
 - 01-10C#通過(guò)重寫Panel改變邊框顏色與寬度的
 - 01-10C#實(shí)現(xiàn)讀取注冊(cè)表監(jiān)控當(dāng)前操作系統(tǒng)已
 
隨機(jī)閱讀
- 01-10使用C語(yǔ)言求解撲克牌的順子及n個(gè)骰子
 - 01-10SublimeText編譯C開發(fā)環(huán)境設(shè)置
 - 08-05dedecms(織夢(mèng))副欄目數(shù)量限制代碼修改
 - 04-02jquery與jsp,用jquery
 - 01-11ajax實(shí)現(xiàn)頁(yè)面的局部加載
 - 01-10C#中split用法實(shí)例總結(jié)
 - 01-11Mac OSX 打開原生自帶讀寫NTFS功能(圖文
 - 01-10delphi制作wav文件的方法
 - 08-05織夢(mèng)dedecms什么時(shí)候用欄目交叉功能?
 - 08-05DEDE織夢(mèng)data目錄下的sessions文件夾有什
 


