Michał Stojek
Michał Stojek

Reputation: 11

C# Linq .Contains list of string

How check in where line.Contains("One") more than one string? For example how select file contains line with text element of "names" List.

private void button_Click(object sender, RoutedEventArgs e)
{
  List<string> names = new List<string>() { "One", "Two", "Three" };

  try
  {
    var files = from file in Directory.EnumerateFiles(@"D:\Logs\", "*.log", SearchOption.AllDirectories)
                from line in File.ReadLines(file)
                where line.Contains("One")
                select new
                {
                  File = file,
                  Line = line
                };

    foreach (var f in files)
    {
      Debug.WriteLine("{0}\t{1}", f.File, f.Line);
    }
    //MessageBox.Show(files.Count().ToString() + " record found.");
    }
  catch (UnauthorizedAccessException UAEx)
  {
    Console.WriteLine(UAEx.Message);
  }
  catch (PathTooLongException PathEx)
  {
    Console.WriteLine(PathEx.Message);
  }
}

Upvotes: 0

Views: 1577

Answers (2)

Csaba Benko
Csaba Benko

Reputation: 1161

You can probably try to use something like this:

line.Intersect(names).Any()

Although, I'm not sure whether it works inside a Linq expression?

Upvotes: 0

Dennis_E
Dennis_E

Reputation: 8894

var files = from file in Directory.EnumerateFiles(@"D:\Stary komp\Logi\Logs2\", "*.log", SearchOption.AllDirectories)
            from line in File.ReadLines(file)
            where names.Any(name => line.Contains(name))
            select new
            {
              File = file,
              Line = line
            };

Upvotes: 4

Related Questions