C # is equivalent to Javascript push

I am trying to convert this code to C # and wondered what is equivalent to Javascript "Array.push"? Here are some lines of code that I convert:

var macroInit1, macroInit2; var macroSteps = new Array(); var i, step; macroInit1 = "Random String"; macroInit2 = "Random String two"; macroSteps.push(macroInit1 + "another random string"); macroSteps.push(macroInit2 + "The last random string"); for (i=0; i<10; i++) { for (step = 0; step < macroSteps.length; step++) { // Do some stuff } } 
+4
source share
3 answers

You can use List<string> :

 var macroInit1 = "Random String"; var macroInit2 = "Random String two"; var macroSteps = new List<string>(); macroSteps.Add(macroInit1 + "another random string"); macroSteps.Add(macroInit2 + "The last random string"); for (int i = 0; i < 10; i++) { for (int step = 0; step < macroSteps.Count; step++) { } } 

Of course, this code looks extremely ugly in C #. Depending on what manipulations you perform on these lines, you can use the LINQ functions built into C # to convert them to a single liner and avoid writing all these imperative loops.

This means that when converting source code from one language to another it is not just a search for an equivalent data type, etc. You can also take advantage of what the target language can offer.

+9
source

You can replace this with

  • List<string> macroSteps for a safe list of types

or

  • ArrayList macroSteps . for a flexible list of objects
+3
source

It can be much cleaner, declarative, and enjoyable in C #, for example:

 //In .NET both lists and arraus implement IList interface, so we don't care what behind //A parameter is just a sequence, again, we just enumerate through //and don't care if you put array or list or whatever, any enumerable public static IList<string> GenerateMacroStuff(IEnumerable<string> macroInits) { { return macroInits .Select(x => x + "some random string or function returns that") //your re-initialization .Select(x => YourDoSomeStuff(x)) //what you had in your foreach .ToArray(); } 

And it can be used then:

 var myInits = new[] {"Some init value", "Some init value 2", "Another Value 3"}; var myMacroStuff = GetMacroStuff(myInits); //here is an array of what we need 

By the way, we can offer you a solution on how to β€œdo things” correctly and beautifully, if you just describe what you want, and not just show us the code that we don’t have, and how to use it, and ask how to translate it literally . Because literal translation can be so unnatural and ugly in the .NET world, and you have to maintain this ugliness ... We do not want you to be in this position :)

+1
source

All Articles