[英]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);
}
}
}
I'm calling this for loop many times over again through timer tick event. 我通过计时器滴答声事件多次调用此for循环。 In the first time the variable t (
List<string>
) contain 43 items. 变量t(
List<string>
)第一次包含43个项目。 And the List<string> newText
contains 172 items. List<string> newText
包含172个项目。
I want to check if any item of t
already exist in newText
not add it again to newText
. 我想检查是否
newText
已经存在t
任何项目,而不是再次将其添加到newText
。
The problem I think is that I'm looping over t.Count
and I should somehow also loop over newText
? 我认为的问题是我正在遍历
t.Count
,我还应该以某种方式遍历newText
吗? How can i fix it so the condition will work fine ? 我该如何解决,这样情况才能正常工作?
If you're using a version of the framework that allows for you to use System.Linq
you can use the Any()
extension: 如果使用的框架版本允许您使用
System.Linq
,则可以使用Any()
扩展名:
newText.Any(r => t.Contains(r));
If there is even one member of newText
that is also found in t
the extension will return true. 如果在
t
也找到了newText
一个成员,则扩展名将返回true。
Edit: as an afterthought you can probably do this even more elegantly with .Except()
extension but I would recommend you get this working in a simple way before you attempt any real optimization. 编辑:事后,您可能可以使用
.Except()
扩展名更加优雅地进行此操作,但是我建议您在尝试任何实际优化之前以一种简单的方式进行操作。
Edit 2: 编辑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.