避免在listview中重复 [英] Avoid duplicates in listview

查看:107
本文介绍了避免在listview中重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在后台同步运行的方法。每次执行时我都会从该方法获取字符串。我在列表视图中添加该字符串。在列表视图中,我创建了一列。我使用以下方法添加项目:



I have a method running synchronously in background. I am getting string from that method each time it executes. I am adding that string in list view. In the list view I created one column. I am adding an item using:

ListViewItem lvi = new ListViewItem();
lvi.text=epc; //epc is the string that I want ti insert in listview
listview1.Items.Insert(0,lvi);





现在我想避免重复我可能会进入字符串'epc'。由于列表框具有lisbox1.contains()属性,因此listview不能使用相同的逻辑。



我尝试过:





Now I want to avoid the duplicates that I may get in the string 'epc'. As the listbox has lisbox1.contains() property, listview doesn't work on same logic.

What I have tried:

if(!lisetView1.items.contains(lvi))
{
    ListViewItem lvi = new ListViewItem();
}





这个逻辑不起作用。我需要一个解决方案来避免重复插入listview。



This logic is not working. I need a solution to avoid duplicates inserting in listview.

推荐答案

问题是你要比较 ListViewItem 对象即使它们可能具有相同的文本,它们也是不同的对象。因此,你的比较并没有达到预期目的。

你可以试试

The problem is that you are comparing ListViewItem objects which, even if they may have the same text, are distinct objects. Thus, your comparison does not achieve what you expect it to.
You could try
using System.Linq;

// ...

if (!listView1.Items.Any(i => i.Text == epc)) {
   listView1.Items.Add(new ListViewItem(epc));
}





编辑:没有Linq的解决方案

如果没有Linq,你必须诉诸旧 - 对集合的迭代迭代:



solution without Linq
Without Linq, you have to resort to old-fashioned iteration over the collection:

bool found = false;
foreach (ListViewItem item in listView1.Items) {
   if (item.Text == epc) {
      found = true;
      break;
   }
}
if (!found) {
   listView1.Items.Add(new ListViewItem(epc));
}


你可以简单地使用一个列表(字符串)。 stringList.Contains(epc)将以您期望的方式工作。
You could simply use a list (of string). stringList.Contains(epc) will work the way you are expecting.


这篇关于避免在listview中重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆