繁体   English   中英

C#String Array包含

[英]C# String Array Contains

有人可以向我解释为什么代码的顶部部分可以工作,但是当测试是一个数组时它没有

        string test = "Customer - ";
        if (test.Contains("Customer"))
        {
            test = "a";
        }

下面的代码不起作用

        string[]test = { "Customer - " };
        if (test.Contains("Customer"))
        {
            test[0]= "a";
        }

在第一种情况下,您调用String.Contains来检查字符串是否包含子字符串。
所以,这个条件返回true

在第二种情况下,您在string[]上调用Enumerable.Contains ,它检查字符串数组是否包含特定值。
由于集合中没有"Customer"字符串,因此返回false

这是两个类似的,但实际上是不同类型的不同方法。

如果要检查集合中的任何字符串是否包含“Customer”作为子字符串,则可以使用LINQ .Any()

if (test.Any(s => s.Contains("Customer"))
{
    test[1] = "a";
}

字符串第一个片段搜索Customer中另一个字符串Customer -这工作,但在第二个片段串Customer搜索内字符串数组,其中一个是Customer - 因此第二个返回false。

从您如何申报测试中可以看出这一点

string test = "Customer - ";

要么

string[] test = { "Customer - " };

注意大括号。 这就是你如何定义一个集合(数组在这里)

要做第二个片段工作,你应该这样做

string[] test = { "Customer - " };
if (test.Any(x => x.Contains("Customer")))
{
    test[1] = "a";
}

因为在第二种情况下,当您在字符串数组中搜索第一个字符串时,if条件为false。 您可以使用任何关键字搜索与客户匹配的数组中的任何字符串,或者您可以搜索test [0]以搜索数组中的第一个字符串(如果它与客户匹配):

if (test[0].Contains("Customer"))
    {
        //your rest of the code here
    }


 if (test.Any(x => x.Contains("Customer")))
    {
        //your rest of the code here
    }
string test = "Customer - ";
if (test.Contains("Customer"))
{
  test = "a";
}

在这个Contains中是一个String类方法,它是IEnumerable检查的基础

“客户 - ”有客户

string[]test = { "Customer - " };
if (test.Contains("Customer"))
{
   test[1]= "a";
 }

在这个Place Contains是一个IEnumerable方法它是IEnumerable checks.So的基础,它不起作用你改变代码

string[] test = { "Customer - " };
if (test.Any(x => x.Contains("Customer")))
{

}

test [1] =“a”它抛出异常因为,数组位置从0开始而不是1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM