Search code examples
c#generic-collections

Collection Variable Question


Lets say that I have a generic collection in the string format. I want to extra the values to a label how would I go about doing that ive tried a few things ive read on here but cant seem to get it to work.

List<string> listcollection= new List<string>();

....Populate Collection Here....

MsgLabel.Text = Controls[string.Format(("MyInts: {0}", listcollection[1].Text));

Any help would be awesome.

Thanks.


Solution

  • There's multiple ways to understand your question:

    • You want to extract the 2nd value and place it in the label, as shown in the example
    • You want to combine all the values into a list (MyInts is plural)

    Extract 2nd value

    MsgLabel.Text = string.Format("MyInts: {0}", listcollection[1]);
    

    To combine them

    You're probably looking for string.Join.

    This would work with the example you've posted:

    MsgLabel.Text = string.Format("MyInts: {0}", string.Join(", ", listcollection));
    

    That code requires .NET 4.0, otherwise string.Join requires an array, so if you're not on 4.0, the following code is what you need:

    MsgLabel.Text = string.Format("MyInts: {0}", string.Join(", ", listcollection.ToArray()));