将数据从csv文件获取到字典中

时间:2013-03-28 20:37:56

标签: c# excel csv

我正在尝试从此文件中获取信息(indexes.csv):

enter image description here

进入这个类的实例:

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;
    }

我想只用特定区域的数据填充字典。

如何从csv文件中执行此操作?

修改

区域的一个例子是字符串值,如“Dalton”

2 个答案:

答案 0 :(得分:2)

我想你想要这样的东西......

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();
            }
        }
    }
}

答案 1 :(得分:0)

首先,您将读取标题并获取包含您所在区域的列的索引。然后你必须读取每一行并用','分割该行,然后读取索引以获得你的价值。您还可以通过搜索拆分记录的第一个索引来应用yr \ qrt。