Jablonovo Jablonovo - 13 days ago 5
C# Question

c# dynamicaly modifying list

Correct! Thanks!
But I don't understand how to do it with foreach...
The goal is to modify a list each time we change Num.
Is the way with a Canvas List and a working List is ok for nice coding?

class Program
{
static void Main(string[] args)
{
int i_Num = 0;
string Str_Num = "";
string[] linkToPLC = {"toto[{0}].test{1}", "tata[{0}].test{1}", "titi[{0}].test{1}"};
List<string> genlnkPLCCanvas = new List<string>(linkToPLC);
List<string> genlnkPLCworkingwith = new List<string>(linkToPLC);

Console.WriteLine("Insert Num: ");
Str_Num = Console.ReadLine();
i_Num = Convert.ToInt32(Str_Num);
for (int item = 0; item < genlnkPLCCanvas.Count; item++)
{
genlnkPLCworkingwith[item] = String.Format(genlnkPLCworkingwith[item], i_Num, 200);
Console.WriteLine("with List: result= " + genlnkPLCworkingwith[item]);
}
//foreach (string item in genlnkPLCCanvas) genlnkPLCworkingwith[item] = String.Format(item, i_Num, 200);
Console.ReadKey();
}
}


Thanks

Answer

If you want to modify the existing list, you have to use for loop instead of foreach one:

 foreach (var item in list) ...

should be changed into

 for (int i = 0; i < list.Count; ++i) {
   var item = list[i]; // not necessary, but often convenient
   ...
   list[i] = ... // modification
   ... 
 }

For instance

   for (int i = 0; i < genlnkPLCCanvas.Count; ++i) {
     var item = genlnkPLCCanvas[i];

     genlnkPLCCanvas[i] = string.Format(item, i_StationNum, 200);
   } 

When testing try creating reports (put all the logic into the single readable query) and then printing them out in one go:

   ...

   var withListReport = genlnkPLC
     .Select(item => "with List: result = " + string.Format(item, i_StationNum, 200)); 

   var withoutListReport = genlnkPLC
     .Select(item => "without List: result = " + string.Format(item, i_StationNum, 200));

   // now you can do whatever you want with the reports: 
   //  - print them to console
   //      Console.WriteLine(string.Join(Envrironment.NewLine, withListReport));
   //  - save to file: File.WriteAllLines(@"C:\MyFile.txt", withListReport);
   //  - print to, say, WinForm UI: 
   //      MyTextBox.Text = string.Join(Envrironment.NewLine, withListReport);

   Console.WriteLine(string.Join(Envrironment.NewLine, withListReport));
   Console.WriteLine(string.Join(Envrironment.NewLine, withoutListReport));

   Console.ReadKey();
Comments