Monday, May 24, 2010

C# "foreach" information?

i'm trying to write a collection array's string elementes longer than 4 in reverse order


foreach (string s in vector) if (s.Length %26gt; 4) Console.WriteLine(s);


worked great but i can't reverse it ... i tried with a normal for but then i can't test vector[i].Length because the object vector does not support Length ... so i'm looking for a way either to reverse my function's members so i can retest with foreach or for an opposite function of foreach

C# "foreach" information?
You could make you're collection inherit ienumerable. That way you can control how the collection is iterated through.





the foreach loop on its own does not give you this control.





The vector[i].ToString().Length should work just fine.


Although if you made your collection a generic of type string I do not believe you would not need to do this because the system would reccognize that the components of vector are a string and wouyld act upon them accordingly.
Reply:I think the only way you are going to be able to do this is to copy the elements into a separate array with each pass of the for...each loop, then go through the array in separate for loop by starting the loop at the (array.Length), then decrementing the counter (counter -= 1) to get the numbers in reverse order. There may be another way, but I don't think you will be able to do it solely through the for...each structure. Good luck : )


No comments:

Post a Comment