![](/img/trans.png)
[英]How do I check if items already exist in a ToolStripMenuItem DropDownItems?
[英]How do i check if items already exist in the List?
for (int i = 0; i < t.Count; i++)
{
if (!newText.Contains(t[i]))
{
if (firsttime > 1)
{
newText.Insert(0, string.Empty);
newText.Insert(0, ExtractLinks.FilteredLinks[i]);
newText.Insert(0, dateTimeList[i]);
newText.Insert(0, t[i]);
}
else
{
newText.Add(t[i]);
newText.Add(dateTimeList[i]);
newText.Add(ExtractLinks.FilteredLinks[i]);
newText.Add(string.Empty);
}
}
}
我通过计时器滴答声事件多次调用此for循环。 变量t( List<string>
)第一次包含43个项目。 List<string> newText
包含172个项目。
我想检查是否newText
已经存在t
任何项目,而不是再次将其添加到newText
。
我认为的问题是我正在遍历t.Count
,我还应该以某种方式遍历newText
吗? 我该如何解决,这样情况才能正常工作?
如果使用的框架版本允许您使用System.Linq
,则可以使用Any()
扩展名:
newText.Any(r => t.Contains(r));
如果在t
也找到了newText
一个成员,则扩展名将返回true。
编辑:事后,您可能可以使用.Except()
扩展名更加优雅地进行此操作,但是我建议您在尝试任何实际优化之前以一种简单的方式进行操作。
编辑2:
static void Main(string[] args)
{
var t = new List<string>(); // starts with 43 items
var newText = new List<string>(); // starts with 172 items
t.AddRange(Enumerable.Range(1, 43).Cast<string>());
newText.AddRange(Enumerable.Range(1, 172).Cast<string>());
// add only members t that do not exist in set newText (44..172 added)
newText.AddRange(t.Except(newText));
}
您可以添加项目并删除所有重复的条目
yourList.Distinct().ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.