C# 字符串数组包含

标签 c# arrays contains

有人可以向我解释为什么代码的顶部有效,但当测试是一个数组时却不起作用吗?

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

下面的代码不起作用

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

最佳答案

在第一种情况下,您调用 String.Contains它检查字符串是否包含子字符串。
因此,此条件返回 true

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

这是两种叫法相似但类型不同的方法。

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

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

关于C# 字符串数组包含,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44916954/

相关文章:

c# - DbExecutionStrategy 重试次数超过 MaxRetryCount

c# - 如何在完成运行后停止计时器?

时间:2019-01-17 标签:c#wpfrichtextboxrunmouseup

javascript - 如何将 Javascript 数组发布到 C# 元组列表?

arrays - 无法在 Swift 中找到接受 'contains' 类型的参数列表的 '(Array<String!>, String)' 重载

python - python 列表的两个 "contains"操作之间的区别

c# - 使用 C# 在 Unity 中绘图

java - 我无法从Java中的数组列表中删除最后一个元素

c++ - 静态二维数组

使用 :contains 的 JQuery 过滤器