我尝试比较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;
}
}
}
答案 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
{
}
}