V.V
V.V

Reputation: 883

Form the String

I need to form the string in for loop.I get the one by one value in "name" variable.Now I need all the value in namevalues variable? the listbox having Pieter,John,Joseph Items.

How can i do this?

  for (int i = 0; i < 2; i++)
    {
      string name = Listboxs.Items[i].ToString();
      string namevalues = ??;
    }

Expected Output is : Pieter*John*Joseph

Upvotes: 3

Views: 79

Answers (3)

m_d_p29
m_d_p29

Reputation: 163

StringBuilder namevalues = new StringBuilder("");

for(int i =0; i<2; i++)
{
    if(namevalues.Length >0 )
    {
        namevalues.Append("*" + Listboxs.Items[i].ToString());
    }
    else
    {
        namevalues.Append(Listboxs.Items[i].ToString());
    }

}

Upvotes: 0

Eric
Eric

Reputation: 5733

Use string.Join with Cast()

var namevalues = string.Join("*", Listboxs.Items.Cast<string>().ToArray());

Upvotes: 0

Soner G&#246;n&#252;l
Soner G&#246;n&#252;l

Reputation: 98740

Since Listboxs.Items returns ListBox.ObjectCollection which implements IEnumerable interface, you can just use string.Join without for loop like;

string.Join("*", Listboxs.Items.Cast<string>());

should return

Pieter*John*Joseph

Upvotes: 9

Related Questions