我有一个由两列组成的文件,这些文件将存储为Dictionary,其中第一列将是键,第二列将是值。第二列由空格分隔,空格可以是任意数量的空格或制表符。

如何使用Split()函数将其存储在字典中?

        recipesFile = new StreamReader(recipesRes.Stream);
        char[] splitChars = {'\t', ' '};

        while (recipesFile.Peek() > 0)
        {
            string recipesLine = "";
            recipesLine = recipesFile.ReadLine();
            string[] recipesInLine = recipesLine.Split(splitChars);

            recipes.Add(recipesInLine[0], recipesInLine[1]);
        }


谢谢

最佳答案

recipesLine.Split(splitChars, StringSplitOptions.RemoveEmptyEntries);


而且您的代码通常可以缩短为

var myDictionary = File.ReadLines(myFileName)
    .Select(l => l.Split(new []{'\t', ' '}, StringSplitOptions.RemoveEmptyEntries))
    .ToDictionary(a => a[0], a => a[1]);

关于c# - C#解析字符串拆分,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10662895/

10-13 00:51