简体   繁体   English

如何比较两个无序ListBox之间的项目

[英]How to compare items between two disordered ListBox

I have 2 ListBoxs which has a set of items. 我有2个ListBoxs ,它有一组项目。 The count between each ListBoxs can be same or different, if the count is same, I want to check if items between the ListBoxs are same. 每个ListBoxs之间的计数可以相同或不同,如果计数相同,我想检查ListBoxs之间的ListBoxs是否相同。 The items can be disordered or ordered as shown below: 物品可能无序或有序,如下所示:

ListBox1 = { "C++", "C#", "Visual Basic" };
ListBox2 = { "C#", "Visual Basic", "C++" };

Kindly help. 请帮助。

You could use Linq's All function 你可以使用Linq的All函数

var ListBox1 = new string[] { "C++", "C#", "Visual Basic" };
var ListBox2 = new string[] { "C#", "Visual Basic", "C++" };
bool same = ListBox1.Length == ListBox2.Length 
   && ListBox1.All(s => ListBox2.Contains(s));

You can simply use HashSet: 你可以简单地使用HashSet:

var hashSet1 = new HashSet<string> { "C++", "C#", "Visual Basic" };
var hashSet2 = new HashSet<string> { "C#", "Visual Basic", "C++" };

var result = hashSet1.SetEquals(hashSet2);

I am assuming these two are two listbox controls 我假设这两个是两个列表框控件

if (ListBox1.Items.Count == ListBox2.Items.Count)
{
    string[] listbox1arr = ListBox1.Items.OfType<string>().ToArray();
    string[] listbox2arr = ListBox2.Items.OfType<string>().ToArray();

    bool flag = listbox1arr.Intersect(listbox2arr).Count() > 0;

    MessageBox.Show(flag : "Items are not same" : "Items are same");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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