역 색인 생성을 시도하지만 작동하지 않습니다. 내 코드에는 오류가 없지만 작동하지 않습니다. 그게 뭐가 잘못 됐니?이 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
어떻게 작동하지 않습니까? 그것은 무엇을 잘못합니까? – hatchet
흔히 코드를 단계별로 실행하고 온 전성 검사를 수행하여 변수에 예상되는 값이 있는지 확인함으로써 버그를 수정할 수 있습니다. 그냥 내 두 센트. –
그냥 마지막 행을 읽을 수 없으므로 이유를 말해 줄 수 있습니까? – Olivia