【问题标题】:assert list string having URL contains sub-string using C# [duplicate]使用 C# 断言具有 URL 的列表字符串包含子字符串 [重复]
【发布时间】:2022-01-23 12:08:42
【问题描述】:

我正在尝试使用 Selenium C# 断言包含从元素的 href 属性中提取的 URL 的字符串列表。下面是我的代码,当我运行它给定的错误时。

    public static void Main()
    {
        List<string> urlList = new List<string>();

    // Adding elements to List
    urlList.Add("https://www.google.com");
    urlList.Add("/app/facebook");
    urlList.Add("https://www.gmail.com");
        
    // Checking whether string is present
    // in List or not
    Console.Write(urlList.Contains("google"));
    }

输出:错误

【问题讨论】:

  • urlList.Contains 检查urlList 中的一项是否为string "google"。而已。如果要检查列表中的字符串是否包含字符串,则必须循环(间接使用 LINQ 或自己编写循环)。

标签: c# selenium-webdriver


【解决方案1】:

试试这个

Console.Write(urlList.Any(x => x.Contains("google")));

【讨论】:

    【解决方案2】:

    使用Any 运算符,用于检查数据源的至少一个元素是否满足给定条件。

     public static void Main()
     {
        List<string> urlList = new List<string>();
        urlList.Add("https://www.google.com");
        urlList.Add("/app/facebook");
        urlList.Add("https://www.gmail.com");
            
        bool isContains = urlList.Any(x => x.Contains("google"));
     }
    

    更多关于Any - https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.any?view=net-6.0

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多