我如何检查,如果列表中的项目已经存在? [英] How do i check if items already exist in the List?

查看:110
本文介绍了我如何检查,如果列表中的项目已经存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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);
        }
    }
}

我通过计时器滴答事件调用此循环多次反复。 在第一时间变量t(名单,其中,串&GT; )包含43项。 而名单,其中,串&GT; newText 包含172项。

I'm calling this for loop many times over again through timer tick event. In the first time the variable t (List<string>) contain 43 items. And the List<string> newText contains 172 items.

我要检查,如果任何项目 T 已经在 newText 存在,不会再次把它添加到 newText

I want to check if any item of t already exist in newText not add it again to newText.

我认为这个问题是我在遍历 t.Count ,我应该以某种方式也环比 newText ? 我该如何解决这样的状况会很好地工作?

The problem I think is that I'm looping over t.Count and I should somehow also loop over newText? How can i fix it so the condition will work fine ?

推荐答案

如果您使用的版本,它允许你使用 System.Linq的你的框架可以使用任何()扩展:

If you're using a version of the framework that allows for you to use System.Linq you can use the Any() extension:

newText.Any(r => t.Contains(r));

如果有一种 newText 这也见于 T 的扩展将返回true,甚至一个成员。

If there is even one member of newText that is also found in t the extension will return true.

编辑:在事后,你也许可以做到这一点更是优雅与。除()扩展,但我会建议你尝试之前,你得到这个工作,以简单的方式任何真正的优化。

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.

编辑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));
    }

这篇关于我如何检查,如果列表中的项目已经存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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