将 Lambda 转化为方法

Lambda into a method

我有一个读取文本文件的方法。 我必须得到文本文件中以 "ART".

开头的单词

我有一个循环遍历该方法的 foreach 循环。

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

}

我的方法是这样的:

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

    }

我在使用方法中的 lambda 时遇到问题,我是使用 lambda 的新手,我真的不知道如何在方法中应用 lambda。

如果我不能很好地解释自己,我很抱歉。

在这里添加即可

foreach (string s in products.Where(lambda))

更新:

您应该像这样将方法更改为 return 产品列表,而不仅仅是单个产品

public static IEnumerable<string> GetProducts(String path, Func<String, bool> lambda)
{
    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.Where(lambda))
        {
            yield return s;
        }
    }
}

你的代码是错误的,因为它只 return 一个字符串,你想要 return 多个字符串,如果产品列表很大,这也可能需要一段时间,我建议这样做:

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

那么使用起来就很简单了:

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

此代码的好处是 return 匹配谓词(lambda)的所有行,以及使用迭代器块执行此操作,这意味着它实际上不会读取下一个排队直到你要求它。