user222427
user222427

Reputation:

.NET string contains string[]

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 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))

Upvotes: 0

Views: 392

Answers (6)

K2so
K2so

Reputation: 982

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

Upvotes: 0

hollystyles
hollystyles

Reputation: 5039

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);

Upvotes: 2

Petar Minchev
Petar Minchev

Reputation: 47393

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

Upvotes: 0

Etienne de Martel
Etienne de Martel

Reputation: 36985

LINQ to the rescue!

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

Upvotes: 10

John Saunders
John Saunders

Reputation: 161801

Try

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

You'll need `using System.Linq;'

Upvotes: 2

cjk
cjk

Reputation: 46465

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)))

Upvotes: 4

Related Questions