2017-05-08 103 views
-5

我在下面有GetWordsArray方法,當我在主程序中調用方法時,它只打印出以特定字母開頭的整個句子。C#收益率返回

public static void GetWordsArray(string path, string toFind) 
    { 
     string[] words = File.ReadAllLines(path); 
     if (File.Exists(path)) 
     {    
      foreach (string line in words) 
      { 
       if(line.StartsWith(toFind)) 
       { 
        Console.WriteLine(line); 
       }     
      } 
     } 
     else 
     { 
      Console.WriteLine("Directory not found"); 
     } 
    } 

這是我如何調用主程序的方法:

Reader r = new Reader();    
    string path = @"randomtext.txt"; 
    Reader.GetWordsArray(path, "b"); 

我如何可以打印出所有的以字母B爲例啓動文本文件中的話嗎?

+4

1.顯示輸出到控制檯的位置,2.爲什麼當循環和返回時返回'lines'? –

+1

爲什麼你要重新實現[File.ReadLines](https://msdn.microsoft.com/en-us/library/dd383503(v = vs.110).aspx)?另外請確保提供[MCVE],其中顯示瞭如何輸出結果。 –

+0

我需要回報它,因爲它是一個學校作業,必須使用它 - - 不知道如何。 – meesie1

回答

0
public class Program 
{ 
    public static void Main(string[] args) 
    { 
     foreach (string item in GetWords(@"C:\Temp\file.txt")) 
     { 
      Console.WriteLine("{0} ", item); 
     } 
    } 

    public static IEnumerable<String> GetWords(string path) 
    { 
     if (File.Exists(path)) 
     { 
      foreach (var line in File.ReadAllLines(path)) 
      { 
       yield return line; 
      } 
     } 
     else 
     { 
      Console.WriteLine("Directory not correct"); 
      yield return null; 
     } 
    } 
} 
+0

'return File.ReadAllLines(path).AsEnumerable();''數組已經是'IEnumerable' - 讀整個文件然後假裝它是懶惰的enumerable是非常奇怪的建議。 –

+0

@AlexeiLevenkov,是的抱歉好點,沒有VS方便,所以扔東西在一起。 –

+0

你能告訴我如何回報它嗎?您提供的代碼很好,但它是一個學校作業,必須遵守要求。 – meesie1

0

可以說你的方法在一個名爲Hello的類上。那麼你可以這樣稱呼它。

Hello hello = new Hello(); 
string path = @"D:\Data\words.txt"; 
var lines = hello.GetWords(path); 
foreach (var line in lines) 
{ 
     Console.WriteLine(line); 
} 

在你的方法中你確實有一些冗餘,因爲你可以簡單地返回行變量,它會以同樣的方式工作。編寫迭代器時使用yield。