2014-02-08 59 views
1

我试过比较两个列表框的mached和not mached项目数量和项目名称。如何比较C#中两个列表框的项目名称?

我想在listMachedItems中显示马库项目名称,马池项目数在lblMachedItemsCount

并在listNotMachedItems中显示NotMached Items Name,NotMached Items Count in lblNotMachedItemsCount

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; 
      } 
     } 
} 
+0

能否请您删除代码中的不必要的空行? –

回答

3
​​
+0

'System.Windows.Forms.ListBox'不包含'ItemsSource'的定义,并且没有找到接受'System.Windows.Forms.ListBox'类型的第一个参数的扩展方法'ItemsSource'(你是否缺少一个using指令或程序集引用?) – user3107343

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

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

我看不到ItemsSource,Intersect,Except.I使用“using System.Windows.Forms;” – user3107343

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 
      { 


      } 

      } 
相关问题