2013-06-02 2 views
0

텍스트 파일이 있는데 모든 짝수 라인을 사전 키에, 모든 짝수 라인을 사전 값에 넣어야합니다. 내 문제에 대한 최선의 해결책은 무엇입니까?txt 파일을 사전 <string, string>으로 변환

int count_lines = 1; 
Dictionary<string, string> stroka = new Dictionary<string, string>(); 

foreach (string line in ReadLineFromFile(readFile)) 
{ 
    if (count_lines % 2 == 0) 
    { 
     stroka.Add Value 
    } 
    else 
    { 
     stroka.Add Key 
    } 

    count_lines++; 
} 
+2

키 - 값 대응이란 무엇입니까? 행 번호'2n-1'은 키이고'2n' 값은? – Andrei

답변

2

당신은 아마이 작업을 수행하려면이 별도로 대신 모든 라인의 두 단계에서 파일을 읽

var array = File.ReadAllLines(filename); 
for(var i = 0; i < array.Length; i += 2) 
{ 
    stroka.Add(array[i + 1], array[i]); 
} 

.

다음과 같은 쌍을 사용하고 싶습니다. (2,1), (4,3), .... 그렇지 않은 경우 필요에 맞게이 코드를 변경하십시오.

+2

자신의 솔루션은 스트리밍 중이지만 사전을 만들기 전에 전체 파일을 메모리에로드해야합니다. 솔루션을 두 번 더 메모리가 필요합니다. –

7

이 시도 :

var res = File 
    .ReadLines(pathToFile) 
    .Select((v, i) => new {Index = i, Value = v}) 
    .GroupBy(p => p.Index/2) 
    .ToDictionary(g => g.First().Value, g => g.Last().Value); 

아이디어는 그룹에 쌍의 모든 라인이다. 각 그룹에는 정확히 두 항목, 즉 첫 번째 항목의 키와 두 번째 항목의 값이 있습니다.

Demo on ideone.

0
String fileName = @"c:\MyFile.txt"; 
    Dictionary<string, string> stroka = new Dictionary<string, string>(); 

    using (TextReader reader = new StreamReader(fileName)) { 
    String key = null; 
    Boolean isValue = false; 

    while (reader.Peek() >= 0) { 
     if (isValue) 
     stroka.Add(key, reader.ReadLine()); 
     else 
     key = reader.ReadLine(); 

     isValue = !isValue; 
    } 
    } 
1

당신은 라인으로 라인을 읽고 사전

public void TextFileToDictionary() 
{ 
    Dictionary<string, string> d = new Dictionary<string, string>(); 

    using (var sr = new StreamReader("txttodictionary.txt")) 
    { 
     string line = null; 

     // while it reads a key 
     while ((line = sr.ReadLine()) != null) 
     { 
      // add the key and whatever it 
      // can read next as the value 
      d.Add(line, sr.ReadLine()); 
     } 
    } 
} 

당신이 사전을 얻을 것이다이 방법에 추가하고, 홀수 라인이있는 경우, 마지막 항목은 null 값을해야합니다 수 있습니다.

관련 문제