C#Linq。包含字符串列表

时间:2016-09-01 12:20:37

标签: c# linq contains

如何检查line.Contains(" One")多个字符串?例如,select文件如何包含文本元素" name"列表。

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

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:0)

您可以尝试使用以下内容:

line.Intersect(names).Any()

虽然,我不确定它是否在Linq表达式中有效?