问题
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]);
}
}
}
I keep getting the error "cannot convert from 'string[]' to 'string'" but cant work out how to fix it.
Thanks in advance!
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!
回答1:
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]);
回答2:
the error is actually because of the ',' you are inputting. It needs an "array" of characters to split from. Here is an example method of splitting using string.split.
string[] parts = line.Split(new string[] { "," }, StringSplitOptions.None);
Hope this helps. this is presuming this is the line the error is coming from as you havn't specified.
来源:https://stackoverflow.com/questions/9791393/loading-a-csv-file-into-dictionary-i-keep-getting-the-error-cannot-convert-fr