2012-10-23 10 views
2

나는 파일에서 큰 (> 1m) 줄의 텍스트를 읽으려면 Yield Return을 사용하는 아래의 방법을 사용합니다.사용 및 수익률로 파일의 텍스트 줄 읽기

private static IEnumerable<string> ReadLineFromFile(TextReader fileReader) 
    { 
     using (fileReader) 
     { 
      string currentLine; 
      while ((currentLine = fileReader.ReadLine()) != null) 
      { 
       yield return currentLine; 
      } 
     } 
    } 

이 메서드에서 반환 된 모든 10 줄을 다른 파일에 쓸 수 있어야합니다.

모든 행을 열거하지 않으면 어떻게이 방법을 사용할 수 있습니까?

모든 답변은 대단히 감사하겠습니다.

+0

이 작동하지 않습니다 작동합니까? – Rym

+0

@ 케빈 무슨 일하지 않니?! :-) – MaYaN

+0

이 코드는 .. 편리한 컴파일러가 없지만 한 번에 10 줄씩 반복 처리하는 것처럼 보입니다. – Rym

답변

1

내가 마지막으로 당신이 아래의 코드를 실행하면, 당신은 당신이 할 필요가 foreach 루프 내에서 메서드를 호출 할 것입니다 볼 수 있습니다, 그리고 그것을 반복합니다

 var listOfBufferedLines = ReadLineFromFile(ReadFilePath); 

     var listOfLinesInBatch = new List<string>(); 
     foreach (var line in listOfBufferedLines) 
     { 
      listOfLinesInBatch.Add(line); 

      if (listOfLinesInBatch.Count % 1000 == 0) 
      { 
       Console.WriteLine("Writing Batch."); 
       WriteLinesToFile(listOfLinesInBatch, LoadFilePath); 
       listOfLinesInBatch.Clear(); 
      } 
     } 

     // writing the remaining lines 
     WriteLinesToFile(listOfLinesInBatch, LoadFilePath); 
0

:-) 일하고있어 생각 한 번에 하나씩, 원하는 크기의 배치 크기로 버퍼링하면됩니다.

static void Main (string [] args) 
{ 
    int batch_size = 5; 
    string buffer = ""; 
    foreach (var c in EnumerateString("THISISALONGSTRING")) 
    {    
     // Check if it's time to split the batch 
     if (buffer.Length >= batch_size) 
     { 
      // Process the batch 
      buffer = ProcessBuffer(buffer); 
     } 

     // Add to the buffer 
     buffer += c; 
    } 

    // Process the remaining items 
    ProcessBuffer(buffer); 

    Console.ReadLine(); 
} 

public static string ProcessBuffer(string buffer) 
{ 
    Console.WriteLine(buffer); 
    return ""; 
} 

public static IEnumerable<char> EnumerateString(string huh) 
{ 
    for (int i = 0; i < huh.Length; i++) { 
     Console.WriteLine("yielded: " + huh[i]); 
     yield return huh[i]; 
    } 
} 
+1

루프에서 문자열을 연결하는 것은 일반적으로 좋은 생각이 아닙니다. – svick

+0

StringBuilder를 사용할 때 강조 표시하는 느낌이 들었습니다. 대답의 범위를 벗어났습니다. – Rym

+1

글쎄, 모든 대답은 모범 사례를 사용해야한다고 생각합니다. 강조 표시 할 필요는 없지만 대답에 사용해야합니다. – svick

0
확실히

하지이 문제를 해결하기위한 우아한 방법,하지만

static void Main(string[] args) 
     { 

      try 
      { 
       System.IO.TextReader readFile = new StreamReader(@"C:\Temp\test.txt"); 
       int count = 0; 
       List<string> lines= new List<string>(); 
       foreach (string line in ReadLineFromFile(readFile)) 
       { 
        if (count == 10) 
        { 
         count = 0; 
         ProcessChunk(lines); 
         lines.Add(line); 
        } 
        else 
        { 
         lines.Add(line); 
         count++; 
        } 

       } 
       //PROCESS the LINES 
       ProcessChunk(lines); 

       Console.ReadKey(); 
      } 
      catch (IOException ex) 
      { 
       Console.WriteLine(ex.ToString()); 
      } 
     } 

     private static void ProcessChunk(List<string> lines) 
     { 
      Console.WriteLine("----------------"); 
      lines.ForEach(l => Console.WriteLine(l)); 
      lines.clear(); 
     } 

     private static IEnumerable<string> ReadLineFromFile(TextReader fileReader) 
     { 
      using (fileReader) 
      { 
       string currentLine; 
       while ((currentLine = fileReader.ReadLine()) != null) 
       { 
        yield return currentLine; 
       } 
      } 
     } 
관련 문제