C# 如何将文本文件转换为词典<;字符串,字符串>;?

C# 如何将文本文件转换为词典<;字符串,字符串>;?,c#,dictionary,C#,Dictionary,我正在视觉工作室为班级制作一个刽子手游戏。我有这个文本文件: LOVE,An intense feeling of deep affection PROCRASTINATION,The action of delaying or postponing something ANNOYED,Slightly irritated HAPPY,A feeling or showing pleasure and contentment EDUCATION,The process of imparting

我正在视觉工作室为班级制作一个刽子手游戏。我有这个文本文件:

LOVE,An intense feeling of deep affection
PROCRASTINATION,The action of delaying or postponing something
ANNOYED,Slightly irritated
HAPPY,A feeling or showing pleasure and contentment
EDUCATION,The process of imparting or acquiring knowledge.
等等。一共有10行。我需要把它们变成一本
字典
,但我不知道怎么做。 以下是我到目前为止的情况:

public class Hangman
{
    //Create fields
    private string _directory = "../../../output/";
    private string _file = "Dictionary.txt";
    private Random _random = new Random();
    private Dictionary<string, string> _words;
    
    

    public Hangman()
    {
        _words = new Dictionary<string, string>();
        string path = _directory + _file;
        if (File.Exists(path))
        {
            using (StreamReader sr = new StreamReader(path))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    //Split up each word and the definiton into a dictionary
                    string words = sr.ReadLine();
                    string[] definitions = words.Split(',');
                    _words.Add(definitions[0], definitions[1]);
公共级刽子手
{
//创建字段
私有字符串_directory=“../../../output/”;
私有字符串_file=“Dictionary.txt”;
私有随机_Random=新随机();
私人词典(单词),;
公众刽子手()
{
_单词=新字典();
字符串路径=_目录+_文件;
if(File.Exists(path))
{
使用(StreamReader sr=新StreamReader(路径))
{
弦线;
而((line=sr.ReadLine())!=null)
{
//把每个单词和定义分成一本字典
字符串字=sr.ReadLine();
string[]definitions=words.Split(',');
_新增(定义[0],定义[1]);
有人能帮我吗?当我用Console.WriteLine编写这个时,它会给我一个永无止境的循环。

你应该仔细阅读如何使用它,以及如何访问它

答案很简单

_words.Add(definitions[0],definitions[1]);
你应该仔细阅读如何使用它,以及如何访问它

答案很简单

_words.Add(definitions[0],definitions[1]);

分割线后:

string line = sr.ReadLine();
string[] lineParts = words.Split(",".ToCharArray());
您可以分配给字典:

_words[lineParts[0]] = lineParts[1];

分割线后:

string line = sr.ReadLine();
string[] lineParts = words.Split(",".ToCharArray());
您可以分配给字典:

_words[lineParts[0]] = lineParts[1];

代码中的一个问题是,您正在将源代码行读入变量
line

while ((line = sr.ReadLine()) != null)
然后在
的同时将
中的另一个
读入变量
words
,然后将该变量拆分为一个数组:

string words = sr.ReadLine();
我不知道为什么循环是永无止境的;事实上,您的代码应该在
之后出错,而
读取最后一行,您尝试拆分空
单词

无论如何,这是可行的:

...
using (StreamReader sr = new StreamReader(path))
{
    string line;
    while ((line = sr.ReadLine()) != null)
    {
        // Split up each word and the definition into a dictionary
        string[] definitions = line.Split(',');
        _words.Add(definitions[0], definitions[1]);
    }
}
...
编辑

参考@Jawad的答案,这里有一个使用
File.ReadAllLines
Linq
的简化版本:

string[] lines = File.ReadAllLines(path);
Dictionary<string, string> _words = lines.ToDictionary(key => key.Split(',')[0], val => val.Split(',')[1]);
string[]line=File.ReadAllLines(路径);
字典_words=lines.ToDictionary(key=>key.Split(',')[0],val=>val.Split(',')[1]);

代码中的一个问题是,您正在将源代码行读入变量

while ((line = sr.ReadLine()) != null)
然后在
的同时将
中的另一个
读入变量
words
,然后将该变量拆分为一个数组:

string words = sr.ReadLine();
我不知道为什么循环是永无止境的;事实上,您的代码应该在
之后出错,而
读取最后一行,您尝试拆分空
单词

无论如何,这是可行的:

...
using (StreamReader sr = new StreamReader(path))
{
    string line;
    while ((line = sr.ReadLine()) != null)
    {
        // Split up each word and the definition into a dictionary
        string[] definitions = line.Split(',');
        _words.Add(definitions[0], definitions[1]);
    }
}
...
编辑

参考@Jawad的答案,这里有一个使用
File.ReadAllLines
Linq
的简化版本:

string[] lines = File.ReadAllLines(path);
Dictionary<string, string> _words = lines.ToDictionary(key => key.Split(',')[0], val => val.Split(',')[1]);
string[]line=File.ReadAllLines(路径);
字典_words=lines.ToDictionary(key=>key.Split(',')[0],val=>val.Split(',')[1]);

您可以一次读取整个文件,而不是一次读取一行。使用
ToDictionary()
方法将字符串列表转换为您要查找的词典

在Linq中,使用
Select
语句为每行生成两个元素的数组(使用
Split
),然后使用
ToDictionary
方法将它们转换为Dictionary

// using System.IO;
// using System.Linq;

string[] lines = File.ReadAllLines(@"../../inputFile.txt");
var _words = lines.Select(x => x.Split(','))
                  .ToDictionary(x => x.First(), y => y.Skip(1).FirstOrDefault())

// OR, Take the string before comma as key, and anything after that as value (including other commas in value)
var _words = lines.ToDictionary(x => x.Split(',').FirstOrDefault(), 
                                y => string.Join(",", y.Split(',').Skip(1)));
您可以使用Newtonsoft.Json序列化程序打印字典

Console.WriteLine(JsonConvert.SerializeObject(_words, Formatting.Indented));

// Prints:
{
  "LOVE": "An intense feeling of deep affection",
  "PROCRASTINATION": "The action of delaying or postponing something",
  "ANNOYED": "Slightly irritated",
  "HAPPY": "A feeling or showing pleasure and contentment",
  "EDUCATION": "The process of imparting or acquiring knowledge."
}

您可以一次读取整个文件,而不是一行一行地读取。使用
ToDictionary()
方法将字符串列表转换为您要查找的词典

在Linq中,使用
Select
语句为每行生成两个元素的数组(使用
Split
),然后使用
ToDictionary
方法将它们转换为Dictionary

// using System.IO;
// using System.Linq;

string[] lines = File.ReadAllLines(@"../../inputFile.txt");
var _words = lines.Select(x => x.Split(','))
                  .ToDictionary(x => x.First(), y => y.Skip(1).FirstOrDefault())

// OR, Take the string before comma as key, and anything after that as value (including other commas in value)
var _words = lines.ToDictionary(x => x.Split(',').FirstOrDefault(), 
                                y => string.Join(",", y.Split(',').Skip(1)));
您可以使用Newtonsoft.Json序列化程序打印字典

Console.WriteLine(JsonConvert.SerializeObject(_words, Formatting.Indented));

// Prints:
{
  "LOVE": "An intense feeling of deep affection",
  "PROCRASTINATION": "The action of delaying or postponing something",
  "ANNOYED": "Slightly irritated",
  "HAPPY": "A feeling or showing pleasure and contentment",
  "EDUCATION": "The process of imparting or acquiring knowledge."
}

这回答了你的问题吗?其余的代码在哪里?这回答了你的问题吗?其余的代码在哪里?但它给了我一个永无止境的循环!首先,我认为你根本不需要
string words=sr.ReadLine()
。删除那一行,然后将下一行改为
string[]definitions=line.Split(','))
如果你不发布整个while循环(不知道你在做什么)。这是while循环中的全部内容,但它给了我一个永无止境的循环。首先,我认为你根本不需要
string words=sr.ReadLine()
。删除那一行,然后将下一行改为
string[]definitions=line.Split(“,”);
如果不发布整个while循环(不确定您还做了什么),就很难看到根本原因。这就是while循环中的全部内容