在监视CSV文件中的现有字符串组合的同时将字符串添加到CSV文件

时间:2017-12-04 23:08:34

标签: c# csv

我试图编写一个C#方法,将一组字符串添加到CSV文件中。就像这样,

public void StoreWords(string expectedValue, stringActualValue)
{
  ///Store expectedValue, actualValue, and a seed value per row in the
  /// .csv file. If the combination of the expectValue and actualValue
  ///does not exist in the .csv file, then initialize a seed value for that 
  ///combination, otherwise increment the seed value for that combination
  }

我在打开csv文件并存储单词组合时遇到困难。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

我认为该代码应符合您的要求:

private string FilePath { get; set; }

private string[] ReadFile()
{
    return File.ReadAllLines(FilePath);
}

public Dictionary<Tuple<string, string>, string> MakeOrIncSeedValuesFromCsv(string[] lines)
{
    var valuePairToSeedValue = new Dictionary<Tuple<string, string>, string>();

    var lines = ReadFile();
    for (int i = 0; i < lines.Length; i++)
    {
        var values = lines[i].Split(',');

        if (values.Length > 2)
        {
            var newSeedValue = IncSeedValue(lines[2]);
            var key = Tuple.Create<string, string>(values[0], values[1]);

            if (!valuePairToSeedValue.ContainsKey(key))
            {
                valuePairToSeedValue.Add(key, newSeedValue);
            }
            else
            {
                valuePairToSeedValue[key] = newSeedValue;
            }

        }
        else
        {
            var key = Tuple.Create<string, string>(values[0], values[1]);
            var seed = GetSeedValue(key);

            if (!valuePairToSeedValue.ContainsKey(key))
            {
                valuePairToSeedValue.Add(key, seed);
            }
            else
            {
                valuePairToSeedValue[key] = seed;
            }
        }
    }

    return valuePairToSeedValue;
}

private string GetSeedValue(Tuple<string, string> values)
{
    return // put your code here
}

private string IncSeedValue(string actualSeedValue)
{
    return // put your code here
}

}