开发者

.NET string contains string[]

开发者 https://www.devze.com 2022-12-25 10:40 出处:网络
I\'m having a small issue putting together this contains statement any help would be awesome. string betaFilePath = @\"C:\\resultsalpha.txt\";

I'm having a small issue putting together this contains statement any help would be awesome.

string betaFilePath = @"C:\resultsalpha.txt";
StringBuilder sb = new StringBuilder();
using (FileStream fs = new FileStream(betaFilePath, FileMode.Open))
using (StreamReader rdr = new开发者_StackOverflow 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);

            }
        }
    }

Error: Argument '1': cannot convert from 'string[]' to 'string' -> if (betaFileLine.Contains(onlythese))


LINQ to the rescue!

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


You can't pass in an array to String.Contains - you will need to loop through your string[] and check each, or use LINQ:

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


Try

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

You'll need `using System.Linq;'


If you have Framework 3.5 use LINQ

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

If not you have to loop each string

bool match = false;

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

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

or use regex

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


Just check for every of them:

bool isOK = false;

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

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


string.Contains accept a single string as parameter instead of a string array.

An easy way is to loop through the onlyThese and nest the contains statement inside:

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;
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消