如何在C#中比较两个列表框的项目名称?

时间:2014-02-08 14:40:45

标签: c# .net winforms

我尝试比较mached和not mached items count以及两个列表框的项目名称。

我想在listMachedItems中显示Mached Items Name,在lblMachedItemsCount中显示Mached Items Count。

并在listNotMachedItems中显示NotMached Items Name,在lblNotMachedItemsCount中显示NotMached Items。

int x = 0;
int y = 0;
for (int i = 0; i < listBox1.Items.Count; i++)
{
    for (int j = 0; j < listBox2.Items.Count; j++)
    {
        if (listBox1.Items[i] == listBox2.Items[j])
        {
            y++;

            //found mached items
            //lblMachedItemsCount.Text = y.ToString() + " " + "items are mached";
            // listMachedItems.Items.Add(listBox1.Items[i].ToString());

             break;

          }
          else
          {
               x++;
               //lblNotMachedItemsCount.Text = x.ToString() + " " + "items are not mached";
               // listNotMachedItems.Items.Add(listBox1.Items[i].ToString());
               break;
           }
      }   
 }

3 个答案:

答案 0 :(得分:3)

listMachedItems.ItemsSource = listBox1.Items.Where(x => listBox2.Items.Contains(x));
listNotMachedItems.ItemsSource = listBox1.Items.Where(x => !listBox2.Items.Contains(x));
lblNotMachedItemsCount.Text = listNotMachedItems.Count() + " items are not matched";
lblMachedItemsCount.Text = listMachedItems.Count() + " items are matched";

答案 1 :(得分:3)

listMatchedItems.Items.AddRange(list1.Intersect(list2).ToArray());
listMachedItemsCount = listMatchedItems.Count();

listNotMatchedItems.Items.AddRange(list1.Except(list2).ToArray());
listNotMachedItemsCount = listNotMatchedItems.Count();

答案 2 :(得分:0)

     var list1 = Enumerable.Intersect(listBox1.Items.Cast<string>().ToArray(), listBox2.Items.Cast<string>().ToArray());
       for (int i = 0; i < listBox1.Items.Count; i++)
       {
           if (list1.Contains(listBox1.Items[i]))
           {


               listBox1.SetSelected(i, true);

               listMatchedItems.Items.Add(listBox1.Items[i]).ToString();
           }

           else

           {

               listNotMatchedItems.Items.Add(listBox1.Items[i]).ToString();
           }


       }

    var list2 = Enumerable.Intersect(listBox2.Items.Cast<string>().ToArray(), listBox1.Items.Cast<string>().ToArray());
       for (int i = 0; i < listBox2.Items.Count; i++)
       {
           if (list2.Contains(listBox2.Items[i]))
           {
               int a = i + 1;
               listBox2.SetSelected(i, true);


           }
           else
           {


           }

           }