C#程序在字符串数组中搜索字符串

使用Linq Contains()方法在字符串数组中搜索特定字符串。

string[] arr = { "Bag", "Pen", "Pencil"};

现在,将字符串添加到字符串变量中,即要搜索的字符串。

string str = "Pen";

使用Contains()方法搜索上面的字符串。

arr.AsQueryable().Contains(str);

让我们看看整个例子。

示例

using System;
using System.Linq;
using System.Collections.Generic;
class Demo {
   static void Main() {
      string[] arr = { "Bag", "Pen", "Pencil"};
      string str = "Pen";
      bool res = arr.AsQueryable().Contains(str);
      Console.WriteLine("String Pen is in the array? "+res);
   }
}

输出结果

String Pen is in the array? True