codingguy3000
codingguy3000

Reputation: 2835

C# Linq query search for a single keyword in multiple text files

You have a directory C:\jimmybuffett\

Inside this directory are two text files: songlist1.txt

Here is the text inside songlist1.txt:

Margaritaville

Boat Drinks

Fins

The second file is: songlist2.txt

Here is the text inside songlist2.txt:

Margaritaville

Boat Drinks Fins

I trying to write a Linq query that search through all files in the folder jimmybuffett and finds files that contain the song title "Fins".

Here is what I have:

using System;
using System.Linq;
using System.IO;

class Program
{
    public static void Main(string[] args)
    {
        String strPath = @"C:\jimmybuffett";
        String strSong = "Fins";

        var songs = from song in Directory.GetFiles(strPath, "*", SearchOption.AllDirectories)
                    where File.ReadAllLines(song).Contains(strSong)
                    select song;

        foreach(var song in songs)
        {
            Console.WriteLine(song);
        }

        Console.WriteLine("Press <enter> to continue");
        Console.ReadLine();
    }
}

This Linq query finds songlist1.txt because the search term "Fins" in on a separate line.

However songlist2.txt is not found because the search term "Fins" is on the same line as "Boat Drinks".

My question is how can I modify my Linq query so that I'm able to identify files that have the search term anywhere in the line.

This would be a like %Fins% SQL query.

I'm aware that I could use a Regular Expression but I'm wondering if I can do this right from my Linq query.

Thanks

Upvotes: 1

Views: 1242

Answers (1)

Cyber Progs
Cyber Progs

Reputation: 3873

you can use Any like this code:

static void Main(string[] args)
        {


        String strPath = @"C:\jimmybuffett";
        String strSong = "Fins";

        var songs = from song in Directory.GetFiles(strPath, "*", SearchOption.AllDirectories)
                    where File.ReadAllLines(song).Any(x=>x.Contains(strSong))
                    select song;

        foreach(var song in songs)
        {
            Console.WriteLine(song);
        }

        Console.WriteLine("Press <enter> to continue");
        Console.ReadLine();
    }

Upvotes: 3

Related Questions