Search code examples
c#lambdastreamreader

Lambda into a method


I have a method where I'm reading a textfile. I have to get the words in the textfile which start with "ART".

I have a foreach loop which loops through the method.

class ProductsList
{
public static void Main()
{
    String path = @"D:\ProductsProjects\products.txt";
    GetProducts(path,  s => s.StartsWith("ART"));
    //foreach (String productin GetProducts(path, s => s.StartsWith("ART"))) 
    //Console.Write("{0}; ", word);

}

My method looks like this:

public static String GetProducts(String path, Func<String, bool> lambda)
{
    try {
        using (StreamReader sr = new StreamReader(path)){
            string[] products= sr.ReadToEnd().Split(' ');
            // need to get all the products starting with ART
            foreach (string s in products){
                return s;
            }

        }
    }

     catch (IOException ioe){
        Console.WriteLine(ioe.Message);
        }
        return ="";
        }

    }

I'm having problems with the lambda in the method, I'm new to working with lambda's and I don't really know how to apply the lambda in the method.

I'm sorry if I can't really explain myself that well.


Solution

  • Your code is wrong in that it only ever returns the one string, you want to return multiple strings, if the list of products is large this could also take a while, I'd recommend doing it this way:

    public static IEnumerable<string> GetProducts(string path, Func<string, bool> matcher)
    {
        using(var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None))
        {
            using(var reader = new StreamReader(stream))
            {
                do
                {
                    var line = reader.ReadLine();
                    if (matcher(line)) yield return line
                }while(!reader.EndOfFile)
            }
        }
    }
    

    Then using it is as simple as:

    foreach(var product in GetProducts("abc.txt", s => s.StartsWith("ART")))
    {
        Console.WriteLine("This is a matching product: {0}", product);
    }
    

    This code has the benefit of returning all of the lines that match the predicate (the lambda), as well as doing so using an iterator block, which means it doesn't actually read the next line until you ask for it.