简体   繁体   中英

C# two listboxes and two lists

I'm trying to get two listboxes to work alongside one another. I'm using Listbox1, Listbox2, List1 and List2 (for this example), the two lists are for further purposes so they need to be included.

Listbox2 should contain everything of List2, listbox1 should contain everything of List1 except for the items in List2. I've been trying alot of different ways, but i just can't seem to get through. Currently Listbox2 gets filled and updated perfectly, but i can't seem to get Listbox1 work accordingly.

Options i've tried (might have written it wrongly) : - add everything of List1 to Listbox1 and then remove everything List2 contains - loop through every List1 item and check if it existed in List2. Add only if it diden't.

Thanks in advance!

I know i'm adding doubles here. I've tried alot of things and removed everything when trying something new (don't ask why, bad habit)

(AddToListbox is a working method.)

if (classroom.members.Count <= 0)
        {
            foreach (Student student in repository.students)
            {
                AddtoListbox(Listbox1, student);
            }
        }
        else
        {
            foreach (Student student in repository.students)
            {
                foreach (Student studentInClass in classroom.members)
                {
                    if (student.LastName != studentInClass.LastName || student.FirstName != studentInClass.FirstName)
                    {
                        AddtoListbox(Listbox1, student);
                    }
                }
            }
        }

尝试对List1 除外

listbox1.AddRange(List1.Except(List2).Cast<object>.ToArray());

I made a little sample waiting on your code. I have a button that populates two List<int> . The First list is 1-20, while the second is 5-9. You will see that it populates Listbox1 with 5-9 and Listbox2 with 1-4 and 10-20.

private void button1_Click(object sender, EventArgs e)
{
     list1 = new List<int>(Enumerable.Range(5,5));
     list2 = new List<int>(Enumerable.Range(1,20));

     foreach (int num1 in list1)
     {
         listBox1.Items.Add(num1);
     }

     foreach (int num2 in list2)
     {
         bool numFound = false;
         foreach (int num1 in list1)
         {
             if (num2 == num1)
             {
                 numFound = true;
                 break;
             }
         }
         if (!numFound)
             listBox2.Items.Add(num2);
     }
}

Not the most eloquent code, but it gets the job done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM