C# 将csv文件中的数据获取到字典中
我正在尝试从此文件(index.csv)获取信息: 到该类的实例中:C# 将csv文件中的数据获取到字典中,c#,excel,csv,C#,Excel,Csv,我正在尝试从此文件(index.csv)获取信息: 到该类的实例中: class Table { Dictionary<String, double> _regionTimeValues; String _region; public Table(String region) { _regionTimeValues = new Dictionary<string, double>(); _region =
class Table
{
Dictionary<String, double> _regionTimeValues;
String _region;
public Table(String region)
{
_regionTimeValues = new Dictionary<string, double>();
_region = region;
suckInValues();
}
private void suckInValues()
{
//Go find File, get the appropriate Values for _region
//add each value found in the csv file that applies, indexed by yearQuarter
//Example: _regionTimeValues.Add("2013Q1", 1.1 );
}
internal double locateRelevantValue(string yearQuarter)
{
double locatedValue = 0.0;
_regionTimeValues.TryGetValue(yearQuarter,out locatedValue);
return locatedValue;
}
类表
{
字典_regionTimeValues;
弦区;
公共表(字符串区域)
{
_regionTimeValues=新字典();
_区域=区域;
吸吮();
}
私人无效票据()
{
//转到查找文件,获取_区域的适当值
//添加csv文件中适用的每个值,按yearQuarter索引
//示例:_regionTimeValues.Add(“2013Q1”,1.1);
}
内部双LocaterElevationValue(字符串yearQuarter)
{
双定位值=0.0;
_regionTimeValues.TryGetValue(yearQuarter,OutLocatedValue);
返回locatedValue;
}
我只想用特定区域的数据填充字典
如何从csv文件执行此操作
编辑
区域的一个示例是类似“道尔顿”的字符串值首先,您将读取标题并获取包含您所在区域的列的索引。然后您必须读取每一行并将该行按“,”拆分,然后读取索引以获取您的值。您还可以通过搜索拆分记录的第一个索引对其应用yr\qrt。我想您需要这样的内容
public class Table
{
private Dictionary<string, double> _regionTimeValues = new Dictionary<string, double>();
private String _region;
public Table(String region)
{
_region = region;
}
public void AddValue(string key, double value)
{
_regionTimeValues.Add(key, value);
}
}
public class Program
{
static void Main(string[] args)
{
Dictionary<string, Table> tables = new Dictionary<string, Table>();
using (var reader = new StreamReader("Data.csv"))
{
// First line contains column names.
var columnNames = reader.ReadLine().Split(',');
for(int i = 1; i < columnNames.Length; ++i)
{
var columnName = columnNames[i];
tables.Add(columnName, new Table(columnName));
}
var line = reader.ReadLine();
while (line != null)
{
var columns = line.Split(',');
for (int i = 1; i < columns.Length; ++i)
{
var table = tables[columnNames[i]];
table.AddValue(columns[0], double.Parse(columns[i]));
}
line = reader.ReadLine();
}
}
}
}
公共类表
{
私有字典_regionTimeValues=新字典();
私有字符串区域;
公共表(字符串区域)
{
_区域=区域;
}
public void AddValue(字符串键,双值)
{
_regionTimeValues.Add(键,值);
}
}
公共课程
{
静态void Main(字符串[]参数)
{
字典表=新字典();
使用(var reader=newstreamreader(“Data.csv”))
{
//第一行包含列名。
var columnNames=reader.ReadLine().Split(',');
for(int i=1;i
什么是区域
示例?用作起点并在其上构建。与可执行文件相关的csv文件需要位于何处?