将CSV文件中的列添加到不同的键

时间:2016-02-29 18:20:15

标签: c# arrays csv dictionary

我有一个包含大量行和列的CSV文件。除了作为帐户名的第一列外,所有行都是不同的。例如,十个不同的帐户名称对于每个帐户名称具有大约100行。因此,对于出现的每个帐户名称,我需要获取该行中所有进行中的列的总和。

这样的csv文件:

史密斯,10,5,9

史密斯,9,5,6

琼斯,10,5,7

jones,9,6,5

需要写入另一个文件:

史密斯,19岁,19岁,15岁

Jones,19,11,12

整个上午都在尝试使用数组或字典来执行此操作,但我似乎无法从逻辑上完成此操作。

    static void Main(string[] args)
    {
        String path = @"C:\Users\jhochbau\documents\visual studio 2015\Projects\CsvReader\CsvReader\Position_2016_02_25.0415.csv";

        string[] lines = File.ReadAllLines(path);
        foreach(string line in lines)
        {
            string[] parsedLine = line.Split(',');
            //for each iteration through the loop where string[0] is already existing
            //I want to have sum = sum + string[1]
        }
        Console.Read();
    }   

我也尝试过使用字典,但最后只有当一个不同的名字出现时才抓住这行。

//To add account as key and each line as value
foreach(var s in data)
{
    string[] temp = s.Split(',');
    //Adds key of account into dictionary, full string line as value.
    dictionary.Add(temp[0], temp);
    foreach (KeyValuePair<string, string[]> accountKeyValuePair in dictionary)
    {
        Console.WriteLine("Account = {}", accountKeyValuePair.Key);   //Additional information: Input string was not in a correct format.
    }
}

寻找类似示例的链接,或者在正确的逻辑方向上轻轻推动。我真的不想为我编写答案。

1 个答案:

答案 0 :(得分:0)

检查一下:

public static void Run()
        {
            var lines = new List<string>() { 
            "Smith, 10, 5, 9",
            "Smith, 9, 5, 6",
            "Jones, 10, 5, 7",
            "Jones, 9, 6, 5"
            };


            var aList = from l in lines                        
                        select new { Name = l.Split(',')[0], Value1 = Convert.ToInt32(l.Split(',')[1]), Value2 = Convert.ToInt32(l.Split(',')[2]), Value3 = Convert.ToInt32(l.Split(',')[3]) };

            var vList = from a in aList
                        group a by a.Name into g
                        select new { Name = g.Key, Value1Sum = g.Sum(a => a.Value1), Value2Sum = g.Sum(a => a.Value2), Value3Sum = g.Sum(a => a.Value3) };

            foreach (var v in vList)
                Console.WriteLine("{0} {1} {2} {3}", v.Name, v.Value1Sum, v.Value2Sum, v.Value3Sum);
        }