如何在c#中将文件复制到字典

sam*_*man 0 c#

如何在c#中将文件复制到字典

Jon*_*eet 5

好吧,您还没有指定文件格式。如果它是“键值”,那么您可以执行以下操作:

string[] lines = File.ReadAllLines("file.txt");
var dictionary = lines.Select(line => line.Split(' '))
                      .ToDictionary(bits => bits[0],
                                    bits => bits[1]);
Run Code Online (Sandbox Code Playgroud)

我实际上并不喜欢一次读取所有行,请注意 - 文件小没问题,但文件大就不好。编写一种一次读取一行的方法相当简单:

public static IEnumerable<string> EnumerableLines(string file)
{
    using (TextReader reader = File.OpenText(file))
    {
        string line;
        while ((line = reader.ReadLine()) != null)
        {
            yield return line;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以针对文本编码等进行调整。

现在查询变成:

var dictionary = EnumerableLines("file.txt")
                      .Select(line => line.Split(' '))
                      .ToDictionary(bits => bits[0],
                                    bits => bits[1]);
Run Code Online (Sandbox Code Playgroud)