2013-05-06 5 views
1

역 색인 생성을 시도하지만 작동하지 않습니다. 내 코드에는 오류가 없지만 작동하지 않습니다. 그게 뭐가 잘못 됐니?이 C# 코드의 문제점

나는이 예외마다 시간을 얻을 :

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.IO; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static Dictionary<TItem, IEnumerable<TKey>> Invert<TKey, TItem>(Dictionary<TKey, IEnumerable<TItem>> dictionary) 
     { 
      return dictionary 
       .SelectMany(keyValuePair => keyValuePair.Value.Select(item => new KeyValuePair<TItem, TKey>(item, keyValuePair.Key))) 
      .GroupBy(keyValuePair => keyValuePair.Key) 
      .ToDictionary(group => group.Key, group => group.Select(keyValuePair => keyValuePair.Value)); 
     } 

     static void Main(string[] args) 
     { 
      Console.WriteLine("files: "); 
      //read all the text document on the specified directory; change this directory based on your machine 
      foreach (string file in Directory.EnumerateFiles("D:\\IR\\", "*.txt")) 
      { 
      string contents = File.ReadAllText(file); 
      Console.WriteLine(contents); 
      Console.Write("find: "); 
      var find = Console.ReadLine(); 
      var dictionary = file.Split().ToDictionary(files => files, files => File.ReadAllText(file).Split().AsEnumerable()); 
      Console.WriteLine("{0} found in: {1}", find, string.Join(" ", Invert(dictionary)[find])); 
      } 
     } 
    } 
} 

KeyNotFoundException was unhandled : the given Key was not present in the dictionary 나는 코드를 편집하고 지금은 오류와 예외없이 작동합니다. 이제는 한 번만 모든 파일을 읽을 수 있어야하는 또 다른 문제가 있습니다. 그러나 매번 그 중 하나를 읽고 나서 프로세스를 찾는 것은 아닙니다. foreach(string file in Dictionary.EnumerateFiles("D:\\IR\\","*.txt"))을 다른 것으로 변경해야합니다. 그러나 나는 그것이 무엇인지 모른다.

출력은 다음과 같이해야합니다 :

파일 : 파일 1 파일 2 파일 3

찾기 : 파일 1 파일 2

+0

어떻게 작동하지 않습니까? 그것은 무엇을 잘못합니까? – hatchet

+2

흔히 코드를 단계별로 실행하고 온 전성 검사를 수행하여 변수에 예상되는 값이 있는지 확인함으로써 버그를 수정할 수 있습니다. 그냥 내 두 센트. –

+0

그냥 마지막 행을 읽을 수 없으므로 이유를 말해 줄 수 있습니까? – Olivia

답변

0

편집 :에있는 어떤

제가 Invert의 버전을 테스트 그게 잘 작동하는 것 같습니다. 기본 ToString() 출력으로 인해 혼란스러워지고 있습니까? Program.Invert(dictionary)[find]을 직접 인쇄하려고하면 기본값 ToString()은 그리 유용하지 않습니다 (인쇄하려고하는 개체가 object.ToString()을 덮어 쓰지 않기 때문에 예상 한 결과를 얻지 못할 것입니다). 값 목록을 반복하여 각 값을 개별적으로 인쇄해야합니다. TKeyToString()을 재정의한다고 가정하면 원하는 결과를 얻을 수 있습니다. 예를 들어, (후손을 위해 저장)

Console.WriteLine("{0} found in: ", find); 
foreach (var val in Program.Invert(dictionary)[find]) 
{ 
    Console.WriteLine(val); 
} 

이전 답변 : 좋아, 당신은 무언가가 당신의 Invert 방법에 잘못 언급했다. 나는 내 자신의 Invert 방법을 쓰려고 애썼다. 나는 분리 된 부분으로 메소드 호출을 분해하여 내가하는 일을 분명히했습니다.

static Dictionary<TItem, IEnumerable<TKey>> Invert<TKey, TItem>(Dictionary<TKey, IEnumerable<TItem>> dictionary) 
{ 
    // Get collection of all the values which will be keys in the new inverted dictionary 
    var invertedDictKeys = dictionary.SelectMany(keyValPair => keyValPair.Value).Distinct(); 

    // Perform the invert 
    var invertedDict = 
     invertedDictKeys.Select(
      invertedKey => 
      new KeyValuePair<TItem, IEnumerable<TKey>>(invertedKey, dictionary.Keys.Where(key => dict[key].Contains(invertedKey)))); 

    // Convert to dictionary and return 
    return invertedDict.ToDictionary(keyValPair => keyValPair.Key, keyValPair => keyValPair.Value); 
} 
+0

아니요, 올바르게 작동하지 않고 분리 된 버전에서도 "키를 찾을 수 없음 예외가 처리되지 않았습니다"라는 동일한 버그가 있습니다. "Directory.EnumerateFiles"를 "Dictionary.GetFiles"로 변경했을 때 작동했지만 문제는 첫 번째 .txt 파일에서만 작동하지만 5 개의 .txt 파일이 있습니다. 또 다른 문제는 버그가 아직 남아있는 유일한 첫 .txt 파일 출력을 얻을 때조차도 마찬가지입니다. 나는 정말로 뭘해야할지 모르겠다는 혼란 스럽다. – Olivia

+0

당신은 예외를 던져야한다고 언급 했어야했다. 일반적으로 SO 질문에서 최대한 많은 정보를 제공하는 것이 좋습니다. –

+0

OK, 이제 어떻게 생각하십니까? 어떤 방법이 있니? – Olivia