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

0 Members and 1 Guest are viewing this topic.

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.  :-)