我有一个包含两列的文件,该文件将存储为字典,其中第一列是键,第二列是值。第二列由空格分隔,可以是任意数量的空格或制表符。
如何使用 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#解析字符串拆分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10662895/