0

I am trying to pass a varying amount of strings into a List and than manipulate these strings. I am attempting something like this but I think I am doing it wrong:

public static void ActivateStateFilter(List<string> lStatelist)
{
    for (int index = 0; index < lStatelist.Count; index++) // Loop with for.
    {
        lStatelist.Add(lStatelist[index]); //Add strings to the list
    }
}

This is how I attempt to pass values:

ActivateStateFilter(new List<string> {"Active", "Inactive"});

Thanks in advance!

8
  • 7
    I don't quite understand what you want to do. You pass a list of strings, an d then you want to add those same strings to the same list again? Commented Apr 28, 2015 at 8:13
  • Why do you think you are doing it wrong? What do you expect your code to do and what do you observe? Commented Apr 28, 2015 at 8:17
  • Could you provide some samples of desired behaivour? Commented Apr 28, 2015 at 8:20
  • I am trying to populate the lStatelist list with varying amount of strings. In this case with just the "Active" and "Inactive" states but it could be more or less from other parts of the code. Commented Apr 28, 2015 at 8:24
  • 1
    Then you don't need any loop at all. Once you do var list=new List<string>(){"Active","Inactive"}; you already have the list. Commented Apr 28, 2015 at 8:30

2 Answers 2

1

You are adding the existing items how new item in the sended list. Your code duplicate lStatelist with their existing items.

What are you really trying to do?

if you are trying to insert your string on specific index use this:

lStatelist.Insert(index, newstring);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for help, how do I use the "newstring" in the function correctly?
@joreldraw if you're not sure of his intent, how can you provide an answer?
1

Your code will throw an OutOfmemoryException, because you create an infinite loop. You are adding the items of a list to the list containing the items… and you are doing this for every item in the list…which will create an infinite loop.

I think you are looking for something like this:

public class Program
{
    private static readonly List<String> _lStateList = new List<String>();

    static void Main( String[] args )
    {
        ActivateStateFilter( new List<String> { "1", "2" } );
    }

    private static void ActivateStateFilter( IEnumerable<String> values )
    {
        _lStateList.AddRange( values );
    }
}

This code will add a range of stirng values to _lStateList

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.