我找到了一些答案,但没有使用mit CSV格式。我想阅读data.csv文件的1.和5.位置并将其存储在字典中:
4096,1000,-,-,Berkeley Trailer nego,[Neil_Sembower]
4097,1001-100F,-,-,Berkeley Trailer encap/IP,[Neil_Sembower]
5632,1600,-,-,Valid Systems,[Neil_Sembower]
16962,4242,-,-,PCS Basic Block Protocol,[Neil_Sembower]
21000,5208,-,-,BBN Simnet,[Neil_Sembower]
24576,6000,-,-,DEC Unassigned (Exp.),[Neil_Sembower]
示例
我需要4097的字符串:
4097,1001-100F, - , - ,Berkeley Trailer encap / IP,[Neil_Sembower]
= Berkeley Trailer encap / I
所以我需要一个带有1.和5.位置的字典(1.键/ 5.值)
有人知道我该怎么做吗?
答案 0 :(得分:2)
这是一种可行的方法:
var pathToCSV = @"C:\...\file.csv"; //define path of csv file here
var lines = File.ReadLines(pathToCSV);
var dictionary = lines.Select(line => line.Split(',')).ToDictionary(data => data[0], data => data[4]);
当然可以更短:
var dictionary = File.ReadLines(@"C:\...\file.csv").Select(line => line.Split(',')).ToDictionary(data => data[0], data => data[4]);
答案 1 :(得分:1)
试试这个:
var reader = new StreamReader(File.OpenRead(@"data.csv"));
var dic = new Dictionary<int, string>();
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
if (!String.IsNullOrEmpty(values[0]))
{
var id = Convert.ToInt32(values[0]);
if (!String.IsNullOrEmpty(values[4]))
{
dic.Add(id, values[4]);
}
}
}