将.csv文件加载到字典中,我不断收到错误“无法从”string []“转换为”string“ [英] Loading a .csv file into dictionary, I keep getting the error "cannot convert from 'string[]' to 'string'"
问题描述
我使用streamreader读取.csv文件,然后我需要分割值并将其放入字典中。到目前为止,我有:
I've used streamreader to read in a .csv file, then i need to split the values and put them into a dictionary. so far i have:
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
Dictionary<string, string> dict = new Dictionary<string, string>();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
using (StreamReader reader = new StreamReader("textwords0.csv"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
string[] parts = line.Split(',');
dict.Add(parts[0], parts[1]);
}
}
}
我不断收到错误不能从'string []'转换为'string',但无法解决如何解决它。
I keep getting the error "cannot convert from 'string[]' to 'string'" but cant work out how to fix it.
提前感谢!
更新:
...我不小心把csv文件打开,现在正在工作,抱歉因为浪费时间,他们认为我有一个不同的电子表格打开,一些非常有用的建议,但感谢所有的帮助
update: ...I accidentally left the csv file open and its working now, sorry for wasting time guys thought i had a different spreadsheet open, some very useful advice though thanks for all the help!
推荐答案
如果您使用 .NET 4.0 ,以下是非常简洁的,应该完成同样的事情:
If you're using .NET 4.0, the following is really succinct and should accomplish the same thing:
var dict = File.ReadLines("textwords0.csv").Select(line => line.Split(',')).ToDictionary(line => line[0], line => line[1]);
这篇关于将.csv文件加载到字典中,我不断收到错误“无法从”string []“转换为”string“的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!