无法将csv文件以原始格式存储到字典中

时间:2017-05-09 21:27:14

标签: c# csv dictionary

拥有以下格式的csv文件: a,b

目标是将此csv文件存储在字典中

问题:csvOne将此作为第一个字段

kfjdfdsdsd, second value

aaaaaaa
sdasdasdaasdasdfffw

因此它不会以原始格式存储,即只存储以下部分:

键:"",值:kfjdfdsdsd

我的代码:

public void StoreInDictionary(string[] file, Dictionary<string, string> dictionary)
        {
            foreach (var line in file)
            {
                var cleansedLine = Regex.Replace(line, @"\s+", "");
                var commaIndex = cleansedLine.IndexOf(',');
                var valueOne = cleansedLine.Substring(0, commaIndex + 1);
                var valueTwo = cleansedLine.Substring(commaIndex + 1);

                if (!dictionary.ContainsKey(valueOne))
                {
                    dictionary.Add(valueOne, valueTwo);
                }
            }
        }

P.S。尝试替换\ r \ n也没用,

非常感谢

2 个答案:

答案 0 :(得分:0)

输出为:

     key               value
kfjdfdsdsd           second value
aaaaaaa              (blank)
sdasdasdaasdasdfffw  (blank)

使用下面的代码

public void StoreInDictionary(string[] file, Dictionary<string, string> dictionary)
{
    foreach (var line in file)
    {
        var cleansedLine = Regex.Replace(line, @"\s+", "");
        var commaIndex = cleansedLine.IndexOf(',');

        string valueOne = String.Empty;
        string valueTwo = String.Empty;

        if (commaIndex > 0)
        {
            valueOne = cleansedLine.Substring(0, commaIndex + 1);
            valueTwo = !String.IsNullOrWhiteSpace(cleansedLine.Substring(commaIndex + 1)) ? 
                        cleansedLine.Substring(commaIndex + 1) : 
                        String.Empty;
        }

        if (!dictionary.ContainsKey(valueOne))
        {
            dictionary.Add(valueOne, valueTwo);
        }
    }
}

答案 1 :(得分:0)

这应该可以满足您的需求。只需快速说明,您可能会有多个“,”,我的解决方案不会解决这个问题。

public void StoreInDictionary(string[] file, Dictionary<string, string> dictionary)
{
    foreach (var line in file)
    {
        if (!string.IsNullOrWhiteSpace(line))
        {
            string valueOne, valueTwo;

            var idx = line.IndexOf(',');

            if (idx >= 0)
            {
                valueOne = line.Substring(0, idx);
                valueTwo = line.Substring(idx + 1);
            }
            else
            {
                valueOne = line;
                valueTwo = string.Empty;
            }

            if (!dictionary.ContainsKey(valueOne))
            {
                dictionary.Add(valueOne, valueTwo);
            }
        }
    }
}