locked
Create a new variable in a loop RRS feed

  • Question

  • How can I make and set a new variable inside a loop i.e.

    foreach(value in list){

    string newvariable = "value in here";

    }

    but every time it goes round I need it to make a newvariable so in the end I may have something like

    newvariable 1 ="1";

    newvariable 2="2";

    newvariable3="3";

    and so on.

    Thanks

    Tuesday, June 24, 2014 3:53 PM

Answers

  • You really cant do exactly that, because variables have to be statically declared. You could use a list;

    List<string> values = new List<string();
    
    foreach(value in list){
        values.Add("value in here");
    }

    But that code is kind of absurd - you already have the list. So, I need to ask the question; what are you trying to achieve here?

    Regards,

    Nick.

    • Proposed as answer by OlofPetterson Wednesday, June 25, 2014 12:16 PM
    • Marked as answer by Anne Jing Wednesday, July 2, 2014 6:03 AM
    Tuesday, June 24, 2014 4:01 PM
  • Use a List<> or an Array (if you are a beginner).

    Here is an array tutorial:

    http://msdn.microsoft.com/en-us/library/aa288453(v=vs.71).aspx

     

    Noam B.


    Do not Forget to Vote as Answer/Helpful, please. It encourages us to help you...

    • Marked as answer by Anne Jing Wednesday, July 2, 2014 6:03 AM
    Wednesday, June 25, 2014 11:32 AM
  • The two approaches are to use an array or a list.  The key difference is that the number of elements in an array is decided once when the array is created and the array will always have that number of elements, whereas a list is a more dynamic kind of container, in that elements can be added or removed and the number of elements in the list can change.

    So an array is a rigid container with a fixed number of elements, and a list is a dynamic container with a variable number of elements.

    To use an array, you have to first decide on how many elements it will have.  Examining your example, it looks like a good choice for the number of elements (the "size" of the list) in this scenario might be the number of elements on the other list that you are iterating over.

    string[] myArrayOfStrings = new string[list.Count];

    To access an element of the array you use syntax like this:  myArrayOfStrings[3]

    The expression you put between the square brackets [ ] is called the index.  Arrays in C# are zero-based, which means that the first element in the array has the index 0.  The second element has the index 1, then 2, 3, 4... and so on.  The last element of the array has an index of N-1 where N is the "size" of the array.  For example, if an array has 10 elements, the index of the last element is 9.

    In your situation you would need to keep track of an index using a local variable.

    int index = 0;
    string[] myArrayOfStrings = new string[list.Count];
    foreach( var item in list )
    {
       myArrayOfStrings[index] = GetStringFromItem( item );
       ++index;
    }

    To get the string used in the 3rd iteration of this loop you can access:

    myArrayOfStrings[2]

    An alternate way of doing this is to use a List as the container.  A List can still be accessed via an index too, but it's way easier to add and remove elements from the list.  In this approach, each time through the loop, we actually add an element to the list, which is initially empty.

    List<string> myListOfStrings = new List<string>();
    foreach( var item in list )
    {
       myListOfStrings.Add( GetStringFromItem( item ) );
    }
    

    You can still access the items in the list by an integer index.  For example, to get the 3rd item in the list:

    myListOfStrings[2]


    And finally, I would be remiss not to at least mention the LINQ approach:

    string[] myListOfStrings = list.Select( item => GetStringFromItem( item ) ).ToArray();


    Or even the more fundamental approach of using an implicitly typed IEnumerable<string> that can become an array or list if necessary later.

    var myQuery = list.Select( GetStringFromItem );


    In this case you can convert myQuery to an array or list at any time.

    List<string> myListOfStrings = myQuery.ToArray();
    
    string[] myArrayOfStrings = myQuery.ToList();

    Side note:  I also have to point out that the "top related threads" for this thread are highly relevant and provide excellent solutions to the same problem you've pitched here.  The related threads are shown when you compose your question before you submit it and you should investigate them before clicking your final submit.

    • Marked as answer by Anne Jing Wednesday, July 2, 2014 6:03 AM
    Wednesday, June 25, 2014 12:39 PM

All replies

  • You really cant do exactly that, because variables have to be statically declared. You could use a list;

    List<string> values = new List<string();
    
    foreach(value in list){
        values.Add("value in here");
    }

    But that code is kind of absurd - you already have the list. So, I need to ask the question; what are you trying to achieve here?

    Regards,

    Nick.

    • Proposed as answer by OlofPetterson Wednesday, June 25, 2014 12:16 PM
    • Marked as answer by Anne Jing Wednesday, July 2, 2014 6:03 AM
    Tuesday, June 24, 2014 4:01 PM
  • Use a List<> or an Array (if you are a beginner).

    Here is an array tutorial:

    http://msdn.microsoft.com/en-us/library/aa288453(v=vs.71).aspx

     

    Noam B.


    Do not Forget to Vote as Answer/Helpful, please. It encourages us to help you...

    • Marked as answer by Anne Jing Wednesday, July 2, 2014 6:03 AM
    Wednesday, June 25, 2014 11:32 AM
  • Just imagine how you will access each variables after you exit the loop?

    Beause each time loop executes variable name will be same overwriting the value of previous value.

    I think idea suggested by Nick will cover your need.


    One good question is equivalent to ten best answers.

    Wednesday, June 25, 2014 11:37 AM
  • The two approaches are to use an array or a list.  The key difference is that the number of elements in an array is decided once when the array is created and the array will always have that number of elements, whereas a list is a more dynamic kind of container, in that elements can be added or removed and the number of elements in the list can change.

    So an array is a rigid container with a fixed number of elements, and a list is a dynamic container with a variable number of elements.

    To use an array, you have to first decide on how many elements it will have.  Examining your example, it looks like a good choice for the number of elements (the "size" of the list) in this scenario might be the number of elements on the other list that you are iterating over.

    string[] myArrayOfStrings = new string[list.Count];

    To access an element of the array you use syntax like this:  myArrayOfStrings[3]

    The expression you put between the square brackets [ ] is called the index.  Arrays in C# are zero-based, which means that the first element in the array has the index 0.  The second element has the index 1, then 2, 3, 4... and so on.  The last element of the array has an index of N-1 where N is the "size" of the array.  For example, if an array has 10 elements, the index of the last element is 9.

    In your situation you would need to keep track of an index using a local variable.

    int index = 0;
    string[] myArrayOfStrings = new string[list.Count];
    foreach( var item in list )
    {
       myArrayOfStrings[index] = GetStringFromItem( item );
       ++index;
    }

    To get the string used in the 3rd iteration of this loop you can access:

    myArrayOfStrings[2]

    An alternate way of doing this is to use a List as the container.  A List can still be accessed via an index too, but it's way easier to add and remove elements from the list.  In this approach, each time through the loop, we actually add an element to the list, which is initially empty.

    List<string> myListOfStrings = new List<string>();
    foreach( var item in list )
    {
       myListOfStrings.Add( GetStringFromItem( item ) );
    }
    

    You can still access the items in the list by an integer index.  For example, to get the 3rd item in the list:

    myListOfStrings[2]


    And finally, I would be remiss not to at least mention the LINQ approach:

    string[] myListOfStrings = list.Select( item => GetStringFromItem( item ) ).ToArray();


    Or even the more fundamental approach of using an implicitly typed IEnumerable<string> that can become an array or list if necessary later.

    var myQuery = list.Select( GetStringFromItem );


    In this case you can convert myQuery to an array or list at any time.

    List<string> myListOfStrings = myQuery.ToArray();
    
    string[] myArrayOfStrings = myQuery.ToList();

    Side note:  I also have to point out that the "top related threads" for this thread are highly relevant and provide excellent solutions to the same problem you've pitched here.  The related threads are shown when you compose your question before you submit it and you should investigate them before clicking your final submit.

    • Marked as answer by Anne Jing Wednesday, July 2, 2014 6:03 AM
    Wednesday, June 25, 2014 12:39 PM