是否可以比较两个列表框及其尊重的选定值?
基本上我想检查列表框A的选定值==列表框B的选定值。
我尝试了这段代码,但它不起作用:
if(listA.SelectedItems == listB.SelectedItems)
{
Console.WriteLine("equal");
}
else
{
Console.WriteLine("not equal");
}
答案 0 :(得分:2)
您可以对SelectedItems
集合进行排序,然后使用SequenceEqual
。
var orderedA = listA.SelectedItems.Cast<object>().OrderBy(x=> x);
var orderedB = listB.SelectedItems.Cast<object>().OrderBy(x=> x);
if(orderedA.SequenceEqual(orderedB))
{
Console.WriteLine("equal");
}
else
{
Console.WriteLine("not equal");
}
答案 1 :(得分:0)
最简单的方法是检查第二个列表中是否包含第一个
中的项目var listAItems = listA.SelectedItems
var listBItems = listB.SelectedItems
if(listAItems.Count == listBItems.Count &&
listAItems.Any(i => !listBItems.Contains(i)))
//Something missing
else
//All there
注意:这适用于所有IEnumerables
我不确定这个答案对你的用法是否比复制品更有效,因为一旦找到一个不存在的条目,它将返回true - 复制答案有可能返回缺少的项目
var missing = listA.SelectedItems.Except(listB.SelectedItems);
if(missing.Any())
//something missing use the missing variable to see what
答案 2 :(得分:0)
您正在使用具有不同含义的两个属性进行比较。 SelectedItem是一个对象(可以是任何东西,取决于你如何填充组合,ValueMember只是一个属性的名称,用作ListBox中项目的实际值。
然而,两个类(ListBox和ComboBox)共享相同的模式来存储它们的列表项,所以假设两个类都使用字符串列表填充,那么你的代码可能是
dynamic curComboItem = ComboBox1.SelectedItem.ToString();
for (i = 0; i <= ListBox1.Items.Count - 1; i++) {
if (curComboItem == ListBox1.Items(i).ToString()) {
Interaction.MsgBox("DATA FOUND");
break; // TODO: might not be correct. Was : Exit For
}
}