【问题标题】:Adding a string to a CSV file while monitoring existing string combinations in the CSV file向 CSV 文件添加字符串,同时监控 CSV 文件中的现有字符串组合
【发布时间】:2017-12-04 23:08:33
【问题描述】:

我正在尝试编写一个将一组字符串添加到 CSV 文件的 C# 方法。会是这样,

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 文件并存储单词组合。任何帮助将不胜感激。

【问题讨论】:

  • 问题太宽泛(问题不止一个……)。首先搜索“如何在 C# 中读取文件”。然后搜索“如何在 c# 中追加到文件”。也许是“如何在 c# 中解析 csv 文件”。然后尝试你学到的东西,如果你遇到困难,再回来提出一个具体的问题。

标签: c# csv


【解决方案1】:

我认为该代码应该满足您的要求:

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
}

}

【讨论】:

  • 在我尝试使用的时候,代码有一个小问题。在 MakeOrIncSeedValuesFromCsv 方法参数中,您有字符串 [] 行。但是在方法内部你有 var 行。这让我自己和编译器感到困惑。在声明的 for 循环中,循环应该增加到的限制基于 line.Length。你指的是哪条线?
  • 另外,我能够实现 IncSeedValue(string actualSeedValue)。但是我遇到了私有字符串 GetSeedValue(Tuple values) 的问题。
  • 从方法中删除这个参数。会好的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-27
  • 2017-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多