Author Topic: Why List<T>.Contains() and List<T>.Exists() both failed?  (Read 4076 times)

0 Members and 1 Guest are viewing this topic.

waterharbin

  • Guest
Why List<T>.Contains() and List<T>.Exists() both failed?
« on: June 22, 2012, 02:15:34 AM »
Hi.
I define a List<LineSegment3d>. And then I define a List<Point3d> to hold the LineSegments' endpoints. Then In a while() loop, I add the StartPoint and the EndPoint to the List<Point3d>, but those two points were not added to the List<Point3d> at the same loop. And noce both the two endpoints are in the List<Point3d>, the LineSegment need to be removed from the List<LineSegment3d> immediately. Here is the pesudocode:
Code: [Select]
        private List<LineSegment3d> vLineLst = new List<LineSegmet3d>();
        private List<Point3d> foundPointLst = new List<Point3d>();

        private void some()
        {
            //In the function, the List<LineSegment3d> will be filled, like:
            //LineSegment3d myLine = new LineSegment3d( startPt,endPt);
            //vLineLst.Add(myline);
        }

        private void some2(List<LineSegment3d> vLst)
        {
            //There is a while() loop here.
            while(condition1)
            {
                //...
                if( condition2 )
                {
                    //....
                    LineSegment3d li = vLst.Find();
                    foundPointLst.Add(li.StartPoint);
                    //....
                }
                //.....
                if( condition3)
                {
                    //....
                    LineSegment3d li = vLst.Find();
                    foundPointLst.Add(li.EndPoint);
                    //....
                }
                //By the way, condition2 and condition3 can never be both true at one loop.

                //Remove the LineSegment from the List<LineSegment3d> once the two endpoints are both checked in the List<Point3d>
                foreach (LineSegment3d vli in vLst)
                {
                       bool existStartPt = foundPointLst.Exists(pt =>
                                {
                                    if (pt == vli.StartPoint)
                                        return true;
                                    return false;
                                });
                      bool existEndPt = foundPointLst.Exists(pt =>
                                {
                                    if (pt == vli.EndPoint)
                                        return true;
                                    return false;
                                });
                      //if (foundPointLst.Contains(vli.StartPoint) && foundPointLst.Contains(vli.EndPoint))    //[color=red]Failed here!!!!![/color]                           
                      if(existStartPt && existEndPt)     //[color=red]Failed here too!!!!!![/color]   
                      {
                           foundPointLst.Remove(vli.StartPoint);
                           foundPointLst.Remove(vli.EndPoint);
                               
                           vLst.Remove(vli);
                           vli.Dispose();
                           //counter++;
                      }
                }   

            }
        }

        [commandMethod("cmd")]
        public void cmd()
        {
            //fill the List<LineSegment3d>
            some();

            //run the function
            some2(vLineLst);
        }
When I test it. The List<LineSegment3d> are full and so does the List<Point3d>. So why?
« Last Edit: June 22, 2012, 02:38:54 AM by 闻仲 »

Kerry

  • Mesozoic relic
  • Seagull
  • Posts: 11654
  • class keyThumper<T>:ILazy<T>
Re: Why List<T>.Contains() and List<T>.Exists() both failed?
« Reply #1 on: June 22, 2012, 02:31:39 AM »

Do you have some code that is compilable ??

Regards
Kdub
kdub, kdub_nz in other timelines.
Perfection is not optional.
Everything will work just as you expect it to, unless your expectations are incorrect.
Discipline: None at all.

waterharbin

  • Guest
Re: Why List<T>.Contains() and List<T>.Exists() both failed?
« Reply #2 on: June 22, 2012, 02:54:48 AM »
Hi,Kerry.
compilable code is available. Yon can try it out. I select lines in the screen to fill the List<LineSegment3d>.
Code - C#: [Select]
  1.  List<Point3d> foundPointLst = new List<Point3d>();
  2.        List<LineSegment3d> lineLst = new List<LineSegment3d>();
  3.  
  4.        int counter = 1;
  5.  
  6.        public bool select()
  7.        {
  8.            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
  9.            Database db = doc.Database;
  10.            Editor ed = doc.Editor;
  11.  
  12.            using (Transaction trans = db.TransactionManager.StartTransaction())
  13.            {
  14.                try
  15.                {                  
  16.                    TypedValue[] tv = new TypedValue[] { new TypedValue((int)DxfCode.Start, "LINE") };
  17.                    SelectionFilter flt = new SelectionFilter(tv);
  18.  
  19.                    PromptSelectionOptions optSel = new PromptSelectionOptions();
  20.                    optSel.MessageForAdding = "Select the lines";
  21.                    PromptSelectionResult resSel = ed.GetSelection(optSel, flt);
  22.                                      
  23.                    if (resSel.Status != PromptStatus.OK)
  24.                        return false;                  
  25.  
  26.                    
  27.                    SelectionSet selSet = resSel.Value;                  
  28.                    ObjectId[] ids = selSet.GetObjectIds();
  29.  
  30.                    
  31.                    foreach (ObjectId sSetEntId in ids)
  32.                    {
  33.                        Entity ent = (Entity)trans.GetObject(sSetEntId, OpenMode.ForWrite);
  34.                        if (ent.GetType().Name == "Line")
  35.                        {
  36.                            Line myLine = (Line)trans.GetObject(sSetEntId, OpenMode.ForWrite);
  37.                            LineSegment3d li = new LineSegment3d(myLine.StartPoint, myLine.EndPoint);
  38.  
  39.                            lineLst.Add(li);
  40.  
  41.                            foundPointLst.Add(li.StartPoint);
  42.                            foundPointLst.Add(li.EndPoint);
  43.                        }
  44.                    }
  45.                }
  46.                catch (System.Exception ex)
  47.                {
  48.                    ed.WriteMessage(ex.Message + "\n" + ex.StackTrace);
  49.                    return false;
  50.                }
  51.  
  52.                trans.Commit();
  53.                return true;
  54.            }
  55.        }
  56.  
  57.        public void eraseLine(List<LineSegment3d> lineLst, List<Point3d> pointLst)
  58.        {
  59.            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
  60.            Database db = doc.Database;
  61.            Editor ed = doc.Editor;
  62.  
  63.            using (Transaction trans = db.TransactionManager.StartTransaction())
  64.            {
  65.                try
  66.                {
  67.                    foreach (LineSegment3d vli in lineLst)
  68.                    {
  69.                        bool existStartPt = pointLst.Exists(pt =>
  70.                        {
  71.                            if (pt == vli.StartPoint)
  72.                                return true;
  73.                            return false;
  74.                        });
  75.                        bool existEndPt = pointLst.Exists(pt =>
  76.                        {
  77.                            if (pt == vli.EndPoint)
  78.                                return true;
  79.                            return false;
  80.                        });
  81.                        //if (pointLst.Contains(vli.StartPoint) && pointLst.Contains(vli.EndPoint))
  82.                        if (existStartPt && existEndPt)
  83.                        {
  84.                            
  85.                            pointLst.Remove(vli.StartPoint);
  86.                            pointLst.Remove(vli.EndPoint);
  87.  
  88.                            
  89.                            lineLst.Remove(vli);
  90.  
  91.                            
  92.                            vli.Dispose();
  93.  
  94.                            counter++;
  95.                        }
  96.                    }
  97.                  
  98.                }
  99.                catch (System.Exception ex)
  100.                {
  101.                    ed.WriteMessage(ex.Message + "\n" + ex.StackTrace);
  102.                    return ;
  103.                }
  104.                trans.Commit();
  105.            }
  106.        }
  107.  
  108.        [CommandMethod("test")]
  109.        public void testLine()
  110.        {
  111.            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
  112.            Database db = doc.Database;
  113.            Editor ed = doc.Editor;
  114.  
  115.            using (Transaction trans = db.TransactionManager.StartTransaction())
  116.            {
  117.                //Initialization
  118.                foundPointLst.Clear();
  119.                lineLst.Clear();
  120.                counter = 1;
  121.                
  122.                //select lines and fill the lists
  123.                if (select())
  124.                {
  125.                    //succes
  126.                    eraseLine(lineLst, foundPointLst);
  127.  
  128.                    
  129.                    //get the counter
  130.                    ed.WriteMessage("\n{0}", counter);
  131.  
  132.                    //output the number
  133.                    ed.WriteMessage("\n line numbers: {0}", lineLst.Count);
  134.                    ed.WriteMessage("\n Points numbers: {0}",foundPointLst.Count);
  135.                }
  136.                else
  137.                {
  138.                    //some stuff when failed to select
  139.                }
  140.  
  141.                trans.Commit();
  142.            }
  143.        }
  144.  

edit:kdub->code formatting code=csharp
« Last Edit: June 22, 2012, 07:01:28 AM by 闻仲 »

Kerry

  • Mesozoic relic
  • Seagull
  • Posts: 11654
  • class keyThumper<T>:ILazy<T>
Re: Why List<T>.Contains() and List<T>.Exists() both failed?
« Reply #3 on: June 22, 2012, 03:45:48 AM »
I wrapped your code in this :
Code - C#: [Select]
  1. using System;
  2. using System.Collections.Generic;
  3. using Autodesk.AutoCAD.ApplicationServices;
  4. using Autodesk.AutoCAD.DatabaseServices;
  5. using Autodesk.AutoCAD.EditorInput;
  6. using Autodesk.AutoCAD.Geometry;
  7. using Autodesk.AutoCAD.Runtime;
  8.  
  9. using xxxxx;
  10. using AcadApp = Autodesk.AutoCAD.ApplicationServices.Core.Application;
  11.  
  12.  
  13. [assembly: CommandClass(typeof(Xxx))]
  14.  
  15. namespace xxxxx
  16. {
  17.     class Xxx
  18.     {
  19.  
  20. //< .... >
  21.  
  22.     }
  23. }


It seems that the
    foreach (LineSegment3d vli in lineLst)
in eraseLine is failing when the count reaches a count of zero
I assume it's because you are deleting each LineSegment3d vli as you itterate the  lineLst.


I don't have  time to take a good look at the code now, but may be able to later.

Regards
kdub


added:
In fact, it fails after the first pass
The error is
{"Collection was modified; enumeration operation may not execute."}
      StackTrace   "   at System.Collections.Generic.List`1.Enumerator.MoveNextRare()\r\n   at xxxxx.Xxx.eraseLine(List`1 lineLst, List`1 pointLst) in D:\\_VSDev\\ACAD\\Testing\\ViewTest\\ViewTest\\TestListT_theSwamp.cs:line 85"
« Last Edit: June 22, 2012, 03:58:21 AM by Kerry »
kdub, kdub_nz in other timelines.
Perfection is not optional.
Everything will work just as you expect it to, unless your expectations are incorrect.
Discipline: None at all.

Delegate

  • Guest
Re: Why List<T>.Contains() and List<T>.Exists() both failed?
« Reply #4 on: June 22, 2012, 06:22:09 AM »
I made some changes to get code to work but I'm unaware of the logic behind the eraseline method as it always returns true. I.e. in the first method you add the start and end points and in the second you check they exist which of course they do. But basically my method would create a new list of lines to prevent you altering the list you are looping on. You could also copy the list and remove from it as required.

I also changed to only one transaction.

I removed the type check on the line as you use a filter so no real need to check it it is a line?

Of course without  knowing what you are trying to do this may not be helpful but was interesting to look through your code   :-)



Code - C#: [Select]
  1. [assembly: CommandClass(typeof(Testing.LineTest))]
  2.  
  3. namespace Testing
  4. {
  5.     class LineTest
  6.     {
  7.         [CommandMethod("linetest")]
  8.         public void testLine()
  9.         {
  10.             Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
  11.             Database db = doc.Database;
  12.             Editor ed = doc.Editor;
  13.  
  14.            
  15.             List<Point3d> foundPointLst = new List<Point3d>();
  16.             List<LineSegment3d> lineLst = new List<LineSegment3d>();
  17.             List<LineSegment3d> newlineLst = new List<LineSegment3d>();
  18.  
  19.             using (Transaction trans = db.TransactionManager.StartTransaction())
  20.             {
  21.                                 //select lines and fill the lists
  22.                 if (selectLINE(trans, lineLst, foundPointLst, ed))
  23.                 {
  24.                     //succes
  25.                    int counter = eraseLine(lineLst, foundPointLst, ed, newlineLst);
  26.  
  27.  
  28.                     //get the counter
  29.                     ed.WriteMessage("\n{0}", counter);
  30.  
  31.                     //output the number
  32.                     ed.WriteMessage("\n line numbers: {0}", newlineLst.Count);
  33.                     ed.WriteMessage("\n Points numbers: {0}", foundPointLst.Count);
  34.                 }
  35.                 else
  36.                 {
  37.                     //some stuff when failed to select
  38.                 }
  39.  
  40.                 trans.Commit();
  41.             }
  42.         }
  43.  
  44.  
  45.  
  46.  
  47.  
  48.         public bool selectLINE(Transaction trans, List<LineSegment3d> lineLst, List<Point3d> foundPointLst, Editor ed)
  49.         {
  50.            
  51.                 try
  52.                 {
  53.                     TypedValue[] tv = new TypedValue[] { new TypedValue((int)DxfCode.Start, "LINE") };
  54.                     SelectionFilter flt = new SelectionFilter(tv);
  55.  
  56.                     PromptSelectionOptions optSel = new PromptSelectionOptions();
  57.                     optSel.MessageForAdding = "Select the lines";
  58.                     PromptSelectionResult resSel = ed.GetSelection(optSel, flt);
  59.  
  60.                     if (resSel.Status != PromptStatus.OK)
  61.                         return false;
  62.  
  63.  
  64.                     SelectionSet selSet = resSel.Value;
  65.                     ObjectId[] ids = selSet.GetObjectIds();
  66.  
  67.                     Line myLine;
  68.                     foreach (ObjectId sSetEntId in ids)
  69.                     {
  70.                        
  71.                             myLine = (Line)trans.GetObject(sSetEntId, OpenMode.ForRead);
  72.                             LineSegment3d li = new LineSegment3d(myLine.StartPoint, myLine.EndPoint);
  73.                             lineLst.Add(li);
  74.                             foundPointLst.Add(li.StartPoint);
  75.                             foundPointLst.Add(li.EndPoint);                            
  76.                        
  77.                     }
  78.                 }
  79.                 catch (System.Exception ex)
  80.                 {
  81.                     ed.WriteMessage(ex.Message + "\n" + ex.StackTrace);
  82.                     return false;
  83.                 }
  84.                
  85.                 return true;
  86.            
  87.         }
  88.  
  89.         public int eraseLine(List<LineSegment3d> lineLst, List<Point3d> pointLst, Editor ed, List<LineSegment3d> newlineLst)
  90.         {
  91.             int counter = 0;
  92.            
  93.                 try
  94.                 {
  95.                     foreach (LineSegment3d vli in lineLst)
  96.                     {
  97.                         bool existStartPt = pointLst.Exists(pt =>
  98.                         {
  99.                             if (pt == vli.StartPoint)
  100.                                 return true;
  101.                             return false;
  102.                         });
  103.                         bool existEndPt = pointLst.Exists(pt =>
  104.                         {
  105.                             if (pt == vli.EndPoint)
  106.                                 return true;
  107.                             return false;
  108.                         });
  109.                         //if (pointLst.Contains(vli.StartPoint) && pointLst.Contains(vli.EndPoint))
  110.                         if (existStartPt && existEndPt)
  111.                         {
  112.  
  113.                             pointLst.Remove(vli.StartPoint);
  114.                             pointLst.Remove(vli.EndPoint);
  115.                             //lineLst.Remove(vli);
  116.                             //vli.Dispose();
  117.                             counter += 1;
  118.                         }
  119.                         else
  120.                         {
  121.                             newlineLst.Add(vli);
  122.                         }
  123.                     }
  124.  
  125.                 }
  126.                 catch (System.Exception ex)
  127.                 {
  128.                     ed.WriteMessage(ex.Message + "\n" + ex.StackTrace);
  129.                    
  130.                 }
  131.                 return counter;
  132.         }
  133.  
  134.     }
  135.  
  136. }
  137.  

waterharbin

  • Guest
Re: Why List<T>.Contains() and List<T>.Exists() both failed?
« Reply #5 on: June 22, 2012, 07:21:35 AM »
Hi.
The compilable codes are just a example. The real codes are divided into too many parts that can not be displayed here. Why I add the endpoints and then remove them? It seems nonsense. But please check my pesudocode at the beginning. The StartPoint and EndPoint are add to the List<Point3d> under different conditions. And those two conditions can never be true at the same time. This means they are added to the List<Point3d> indenpedently,not at the same time in the compilable code. So,in the foreach (LineSegment3d vli in lineLst) in eraseLine, not every itterate there will be a line removed.
The big problem is: I want remove the LineSegment from its own List immedately once its StartPoint and EndPoint have been checked in the List<Point3d>. As Kerry said. the foreach (LineSegment3d vli in lineLst) stopped when a "vli" removed from the List. The "lineLst" changed so the foreach can never go ahead. Is there any other way. Remove the LineSegment immediately is very important.
« Last Edit: June 22, 2012, 07:35:51 AM by 闻仲 »

Kerry

  • Mesozoic relic
  • Seagull
  • Posts: 11654
  • class keyThumper<T>:ILazy<T>
Re: Why List<T>.Contains() and List<T>.Exists() both failed?
« Reply #6 on: June 22, 2012, 07:26:20 AM »
Quote
So,in the foreach (LineSegment3d vli in lineLst) in eraseLine, not every itterate there will be a line removed.
The big problem is: I want remove the LineSegment from its own List immedately once its StartPoint and EndPoint have been checked in the List<Point3d>.

That MAY be what you want to do, but not what you coded.
What is the point of providing sample code if it's not a real sample of your problem

That's a waste of time and effort for each of us.
kdub, kdub_nz in other timelines.
Perfection is not optional.
Everything will work just as you expect it to, unless your expectations are incorrect.
Discipline: None at all.

waterharbin

  • Guest
Re: Why List<T>.Contains() and List<T>.Exists() both failed?
« Reply #7 on: June 22, 2012, 07:44:56 AM »
Hi,Kerry. My sample code showed my problem too. I intend to give the shortest code, so you don't need to read 1000 lines, most of which are just simple codes. I think that would be a waste of time and effort. That's why I write a sample alone, not just simply post a lot of codes here.
You do find the problem here for me, so I appreciate that.
« Last Edit: June 22, 2012, 08:21:09 AM by 闻仲 »

Delegate

  • Guest
Re: Why List<T>.Contains() and List<T>.Exists() both failed?
« Reply #8 on: June 22, 2012, 07:51:44 AM »
Think you can only either create a copy of the list to loop through and amend the original or use a for loop as shown below:

Code - C#: [Select]
  1.  for (int i = 0; i < lineLst.Count; i++)
  2.               {          
  3.                        
  4.                    lineLst.RemoveAt(i);
  5.                     i--;
  6.                            
  7.               }

waterharbin

  • Guest
Re: Why List<T>.Contains() and List<T>.Exists() both failed?
« Reply #9 on: June 22, 2012, 08:16:21 AM »
Hi,Delegate. That's just what I am thinking about too. Haha.
Loop the copy List, get the index, and then use the index to remove the line in the original List. That costs. Beause the copy List need to be updated every loop is finished. I prefer the for loop.

Keith™

  • Villiage Idiot
  • Seagull
  • Posts: 16899
  • Superior Stupidity at its best
Re: Why List<T>.Contains() and List<T>.Exists() both failed?
« Reply #10 on: June 22, 2012, 08:37:19 AM »
If I was going to place items into a list structure then at some point delete them, I would probably create a stack instead of a list, then push all of the items onto the stack. After the stack is created, pop them off one at a time to test them, if it is something I want to save, push it to a different stack. When the first stack is empty, the second stack will contain all of the items you want to save.
Proud provider of opinion and arrogance since November 22, 2003 at 09:35:31 am
CadJockey Militia Field Marshal

Find me on https://parler.com @kblackie

waterharbin

  • Guest
Re: Why List<T>.Contains() and List<T>.Exists() both failed?
« Reply #11 on: June 22, 2012, 09:05:02 AM »
Hi,Keith. Thanks for the "Stack" suggestion. I will try it the next time I mess up with this kind of problem. But at this time, the List is involved in many other parts in a big project. It will cost more to the replace the List with Stack. Haha.

waterharbin

  • Guest
Re: Why List<T>.Contains() and List<T>.Exists() both failed?
« Reply #12 on: June 22, 2012, 10:06:37 AM »
Hi. What about this one. It seems to work.Haha.
Code - C#: [Select]
  1. public void eraseLine(List<LineSegment3d> lineLst, List<Point3d> pointLst)
  2.        {
  3.            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
  4.            Database db = doc.Database;
  5.            Editor ed = doc.Editor;
  6.  
  7.            using (Transaction trans = db.TransactionManager.StartTransaction())
  8.            {
  9.                try
  10.                {
  11.                    //&#23450;&#20041;&#19968;&#20010;&#20803;&#32032;&#32034;&#24341;&#30340;List
  12.                    //Hold the index for the lines which need to be removed
  13.                    List<int> indexLst = new List<int>();
  14.                    for (int i = 0; i < lineLst.Count; i++)
  15.                    {
  16.                        if (pointLst.Contains(lineLst[i].StartPoint) &&
  17.                            pointLst.Contains(lineLst[i].EndPoint))
  18.                        {
  19.                            indexLst.Add(i);
  20.                        }
  21.                    }
  22.                    //&#23558;&#32034;&#24341;&#31446;&#30452;&#21453;&#36716;&#65292;&#35753;&#32034;&#24341;&#20540;&#22823;&#30340;&#22312;&#21069;&#65292;&#20540;&#23567;&#30340;&#22312;&#21518;
  23.                    //Once a element is removed,the index for the following element is changed too, so we need to remove the element backward.
  24.                    //Remove the one with the big index, so the smaller index will not be affected
  25.                    indexLst.Reverse();
  26.                    
  27.                    //&#20174;&#21518;&#24448;&#21069;&#21024;&#38500;&#36873;&#23450;&#30340;&#30452;&#32447;&#27573;
  28.                    //Remove the big index first.
  29.                    foreach (int i in indexLst)
  30.                    {
  31.                        //remove the point
  32.                        pointLst.Remove(lineLst[i].StartPoint);
  33.                        pointLst.Remove(lineLst[i].EndPoint);
  34.  
  35.                        //remvoe the line
  36.                        lineLst.RemoveAt(i);                      
  37.                    }
  38.                    /*
  39.                    /*
  40.                    foreach (LineSegment3d vli in lineLst)
  41.                    {
  42.                        bool existStartPt = pointLst.Exists(pt =>
  43.                        {
  44.                            if (pt == vli.StartPoint)
  45.                                return true;
  46.                            return false;
  47.                        });
  48.                        bool existEndPt = pointLst.Exists(pt =>
  49.                        {
  50.                            if (pt == vli.EndPoint)
  51.                                return true;
  52.                            return false;
  53.                        });
  54.                        //if (pointLst.Contains(vli.StartPoint) && pointLst.Contains(vli.EndPoint))
  55.                        if (existStartPt && existEndPt)
  56.                        {
  57.                            
  58.                            pointLst.Remove(vli.StartPoint);
  59.                            pointLst.Remove(vli.EndPoint);
  60.  
  61.                            
  62.                            //lineLst.Remove(vli);
  63.  
  64.                            
  65.                            //vli.Dispose();
  66.  
  67.                            counter++;
  68.                        }
  69.                    }
  70.                    */
  71.                  
  72.                }
  73.                catch (System.Exception ex)
  74.                {
  75.                    ed.WriteMessage(ex.Message + "\n" + ex.StackTrace);
  76.                    return ;
  77.                }
  78.                trans.Commit();
  79.            }
  80.        }
  81.  

edit:kdub->code formatting code=csharp
« Last Edit: June 22, 2012, 08:07:18 PM by Kerry »

Jeff H

  • Needs a day job
  • Posts: 6150
Re: Why List<T>.Contains() and List<T>.Exists() both failed?
« Reply #13 on: June 22, 2012, 12:16:39 PM »
You cannot modify the underlying collection using a Enumerator.
Plenty of information out there that explains why and how they work.
 
Not sure what you are exactly trying to do but to help show why it is failing just change the foreach to
Code - C#: [Select]
  1. foreach (LineSegment3d vli in new List<LineSegment3d>(lineLst))
  2.  

now the enumerator is working with a copy and
Code - C#: [Select]
  1. lineLst.Remove(vli);
  2.  

does not modify the underlying collection

MSDN
 

waterharbin

  • Guest
Re: Why List<T>.Contains() and List<T>.Exists() both failed?
« Reply #14 on: June 26, 2012, 02:10:32 AM »
Hi,Jeff. Thanks for your solution. But you still need to define a new List.
Anyhow, I am very aware that I can never change a List when iterating it, not for loop or foreach loop. Haha.

gile

  • Gator
  • Posts: 2507
  • Marseille, France
Re: Why List<T>.Contains() and List<T>.Exists() both failed?
« Reply #15 on: June 26, 2012, 06:19:27 AM »
Quote
Anyhow, I am very aware that I can never change a List when iterating it, not for loop or foreach loop. Haha.

You can't with foreach (a foreach iteration variable cannot be assigned), but you can with for.

Code - C#: [Select]
  1.         static void Main()
  2.         {
  3.             List<int> lst = new List<int>(4) { 0, 1, 2, 3 };
  4.             Print(lst);
  5.             for (int i = 0; i < lst.Count; i++)
  6.             {
  7.                 lst[i] += 10;
  8.             }
  9.             Print(lst);
  10.             Console.ReadKey();
  11.         }
  12.  
  13.         static void Print<T>(IEnumerable<T> collection)
  14.         {
  15.             foreach (T item in collection)
  16.             {
  17.                 Console.WriteLine(item);
  18.             }
  19.         }
« Last Edit: June 26, 2012, 06:23:32 AM by gile »
Speaking English as a French Frog

waterharbin

  • Guest
Re: Why List<T>.Contains() and List<T>.Exists() both failed?
« Reply #16 on: June 26, 2012, 08:25:16 AM »
Hi,gile.Thanks for that. I feel like I was an export on computer science already.Haha. You people do teach me a lot.  :-)