读本地的CSV表

读本地的CSV表_第1张图片

读这个csv文件

/// 
    /// 读入csv表
    /// 
    class DataCenter
    {
        private Dictionary<string, int> dictName = new Dictionary<string, int>();
        private Dictionary<int, List<double>> dictData = new Dictionary<int, List<double>>();

        public DataCenter()
        {
            using (System.IO.StreamReader sr = new System.IO.StreamReader(System.IO.File.Open(@"C:\Users\XX\Desktop\XXXXXX.csv", System.IO.FileMode.Open)))
            {
                int nINdex = 0;
                while (sr.EndOfStream == false)
                {
                    string szLine = sr.ReadLine();
                    // skip first line
                    if (nINdex == 0)
                    {
                        string[] allNames = szLine.Split(',');
                        int nNameIndex = 0;
                        foreach (string entity in allNames)
                        {
                            dictName.Add(entity, nNameIndex);
                            nNameIndex++;
                        }
                    }
                    else
                    {
                        string[] fileds = szLine.Split(',');

                        List<double> listData = new List<double>();
                        foreach (string entity in fileds)
                        {
                            listData.Add(double.Parse(entity));
                        }

                        dictData.Add(nINdex, listData);
                    }
                    nINdex++;
                }
            }
        }


        public List<string> GetVariableName()
        {
            return dictName.Keys.ToList<string>();
        }

        // 变量名称
        // nTimeStamp 时间戳
        public double GetData(string variableName, int nTimeStamp)
        {
            double dVAlue = 0.0f;

            if (dictName.ContainsKey(variableName))
            {
                int nIndex = dictName[variableName];

                if (dictData.ContainsKey(nTimeStamp))
                {
                    dVAlue = dictData[nTimeStamp][nIndex];
                }
            }

            return dVAlue;
        }
    }

你可能感兴趣的:(读本地的CSV表)