eltel2910
eltel2910

Reputation: 345

Combine items from two listboxes into a third listbox

I am trying to combine the contents of two listboxes such that if ListBox 1 has A,B,C in it and ListBox 2 has 1,2,3 in it, the output in ListBox 3 would be: A1,A2,A3,B1,B2,B3,C1,C2,C3. My code below almost does that, but it writes over the A and B iterations and only shows the C iteration. What am I missing here?

string A; string B;

private void button1_Click(object sender, EventArgs e)
{
    for (int i = 0; i < listBox1.Items.Count; i++)
    {
        A =  listBox1.Items[i].ToString();
    }
    for (int j = 0; j < listBox2.Items.Count; j++)
    {
        B = listBox2.Items[j].ToString();
        listBox3.Items.Add(A + ": " + B);
    }
}

Upvotes: 2

Views: 1477

Answers (3)

Enigmativity
Enigmativity

Reputation: 117057

If you want to use LINQ then this works nicely:

        var items =
            from A in listBox1.Items.Cast<string>()
            from B in listBox2.Items.Cast<string>()
            select A + ": " + B;

        listBox3.Items.AddRange(items.ToArray());

Upvotes: 2

Tetramputechture
Tetramputechture

Reputation: 2921

private void button1_Click(object sender, EventArgs e)
{
    for (int i = 0; i < listBox1.Items.Count; i++)
    {
        A =  listBox1.Items[i].ToString();
        for (int j = 0; j < listBox2.Items.Count; j++)
        {
            B = listBox2.Items[j].ToString();
            listBox3.Items.Add(A + ": " + B);
        }
    }
}

I moved the second for loop into the first one. This should work.

Upvotes: 2

MarcinJuraszek
MarcinJuraszek

Reputation: 125620

Yes, you're missing the fact, that first loop is over when second one starts. And that's why A is always the last value from first listbox. Nest the loops instead:

private void button1_Click(object sender, EventArgs e)
{
    for (int i = 0; i < listBox1.Items.Count; i++)
    {
        A =  listBox1.Items[i].ToString();

        for (int j = 0; j < listBox2.Items.Count; j++)
        {
            B = listBox2.Items[j].ToString();

            listBox3.Items.Add(A + ": " + B);
        }
    }
}

Upvotes: 3

Related Questions