.NET字符串包含字符串[]

时间:2010-03-31 14:13:39

标签: c#

我有一个小问题,把这个包含声明放在一起,任何帮助都会很棒。

string betaFilePath = @"C:\resultsalpha.txt";
StringBuilder sb = new StringBuilder();
using (FileStream fs = new FileStream(betaFilePath, FileMode.Open))
using (StreamReader rdr = new StreamReader((fs)))
{
    while (!rdr.EndOfStream)
    {
        string betaFileLine = rdr.ReadLine();
        {
            string[] onlythese = {@"apple/",@"aee/",@"www/",@"blk/",@"art/",@"purp/",@"ora/",@"red/",@"brd/",@"biek/",@"biz/"};
            if (betaFileLine.Contains(onlythese))
            {
                File.AppendAllText(@"C:\testtestest.txt", betaFileLine);

            }
        }
    }

错误:参数'1':无法从'string []'转换为'string' - > if(betaFileLine.Contains(onlythese))

6 个答案:

答案 0 :(得分:10)

LINQ救援!

if(onlythese.Any(str => betaFileLine.Contains(str)))
{
    // ...
}

答案 1 :(得分:4)

您无法将数组传递给String.Contains - 您需要循环遍历字符串[]并检查每个数组,或使用LINQ:

if(onlythese.Any(a => betaFileLine.Contains(a)))

答案 2 :(得分:2)

尝试

if (onlythese.Any(only => betaFileLine.Contains(only))

你需要`使用System.Linq;'

答案 3 :(得分:2)

如果你有Framework 3.5使用LINQ

if(onlythese.Any(s => betaFileLine.Contains(s)))
{
    File.AppendAllText(@"C:\testtestest.txt", betaFileLine);
}

如果不是,你必须循环每个字符串

bool match = false;

foreach(String thisString in onlyThese)
{
    if(betaFileLine.Contains(thisString)
    {
        match = true;
        break;
    }
}

if(match)
    File.AppendAllText(@"C:\testtestest.txt", betaFileLine);

或使用正则表达式

string onlyThese = @"apple/|aee/|www/|blk/|art/|purp/|ora/|red/|brd/|biek/|biz/";
if (Regex.IsMatch(betaFileLine, onlyThese))
    File.AppendAllText(@"C:\testtestest.txt", betaFileLine);

答案 4 :(得分:0)

只需检查每一个:

bool isOK = false;

foreach (string current in onlythese)
  if (betaFileLine.Contains(current))
  {
     isOK = true;
     break;
  }

if (isOK)
{
   File.AppendAllText(@"C:\testtestest.txt", betaFileLine);
}

答案 5 :(得分:0)

string.Contains接受单个字符串作为参数而不是字符串数组。

一种简单的方法是遍历onlyThese并将contains语句嵌套在其中:

string[] onlythese = {@"apple/",@"aee/",@"www/",@"blk/",@"art/",@"purp/",@"ora/",@"red/",@"brd/",@"biek/",@"biz/"};
foreach(string onlyThis in onlythese) 
{
    if (betaFileLine.Contains(onlyThis))
    {
        File.AppendAllText(@"C:\testtestest.txt", betaFileLine);
        break;
    }
}