I am curious as to what is the best way to modify a list in c#. As far as I'm aware, the foreach loop is used to iterate over the list to get the desired information and if you need to modify the list then use a for loop. I have found 3 ways to modify a list but they all seem to pretty much remove the items as intended.
So my questions are:
1) What is the difference between these 3 ways shown below?
2) is there a specific time where one of them should be used over the other way?
3) Is there any other better ways to modify a list?
4) When removing you are meant to reverse the list, is this simply to not mess up the order and cause unpredictable side effects?
Reverse for loop:
List<int> integerListForReverse = new List<int>();
for(int i = 0; i <10; i ++)
{
integerListForReverse.Add(i);
}
for (int i = integerListForReverse.Count - 1; i >= 0; i--)
{
int ints = i;
if(ints % 2 == 0)
{
integerListForReverse.Remove(ints);
Console.WriteLine(ints + " reverse for loop");
}
}
Create a copy of the list
List<int> integerListForeachCopy = new List<int>();
for (int i = 0; i < 10; i++)
{
integerListForeachCopy.Add(i);
}
foreach (int ints in integerListForeachCopy.ToList())
{
if (ints % 2 == 0)
{
integerListForeachCopy.Remove(ints);
Console.WriteLine(ints + "copy of the list ");
}
}
Reverse foreach loop
List<int> integerListReverseForeach = new List<int>();
for (int i = 0; i < 10; i++)
{
integerListReverseForeach.Add(i);
}
foreach (int ints in integerListReverseForeach.Reverse<int>())
{
if (ints % 2 == 0)
{
integerListReverseForeach.Remove(ints);
Console.WriteLine(ints + "reverse foreach");
}
}
Just a few things that were confusing me and would like cleared up.
Thank you in advance.