[英]How can we match string contains any value of array in C# w/o using loop?
How can we match string contains any value of array in C# w/o using loop?我们如何在不使用循环的情况下匹配包含 C# 中数组的任何值的字符串?
For example:例如:
string[] abc= [val1,val2,val3] . string[] abc= [val1,val2,val3] 。 string xyz= "demo string to check if it contains any value in abc array that is val2"; string xyz="演示字符串,检查它是否包含 abc 数组中的任何值,即 val2";
I want to check if any value of array abc exists in string xyz w/o using loop我想使用循环检查字符串 xyz 中是否存在数组 abc 的任何值 w/o
one aproach may be linq一种方法可能是 linq
string[] abc = { "abc", "def", "xyz" };
string xyz = "demo string to check if it contains any value in abc array that is val2";
bool result = abc.Any(xyz.Contains); //true
but internal linq and contains uses loop - so i think there is no possible solution without a loop.但是内部 linq 和 contains 使用循环 - 所以我认为没有循环就没有可能的解决方案。
To search from/in a collection (read array), you need to use loops/iteration because collection is involved.要从/在集合中搜索(读取数组),您需要使用循环/迭代,因为涉及到集合。
Even if you do not write a loop and write some syntactic sugar code, in the background it will use LOOP/ITERATION.即使你不写循环,写一些语法糖代码,在后台它也会使用 LOOP/ITERATION。
As others answered you can use LINQ or something but it will iterate over your collection.正如其他人回答的那样,您可以使用 LINQ 或其他东西,但它会遍历您的集合。
There is already a contains function.已经有一个包含功能。 you may use it like this你可以这样使用它
bool result=abc.Contains("walue to be checked");
Alternate way is by using LINQ替代方法是使用 LINQ
but both the method use internal loops.但是这两种方法都使用内部循环。
you can check as :您可以检查为:
string[] arr = { "abc", "bcd", "cde" };
if (arr.Contains("abc"))
{
Console.WriteLine("Found");
}
else
{
Console.WriteLine("Not Found");
}
For faster way you can use Array.IndexOf Method :对于更快的方法,您可以使用Array.IndexOf 方法:
int pos = Array.IndexOf(arr, "abc");
if (pos > -1)
{
// the array contains the string and the pos variable
// will have its position in the array
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.