2016-02-29 67 views
0

我有一个CSV文件,它有许多行和列。除了第一列将是一个帐户名称以外,所有行都将不同。例如,有10个不同的帐户名称,每个帐户名称大约有100行。因此,对于出现的每个帐户名称,我需要为该行中所有正在进行的列获得一笔总和。将CSV文件中的列添加到不同的键

所以csv文件是这样的:

史密斯,10,5,9

史密斯,9,5,6和

琼斯,10,5,7

琼斯9,6,5

需要被写入到这样的另一个文件:

史密斯,19,1 9,15

琼斯,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. 
    } 
} 

寻找一个链接到一个类似的例子,或者可能是一个温柔的微调在正确的逻辑方向。我真的不想为我编码的答案。

+0

你熟悉'控制Break'处理..你可以通过创建一个模仿类做这个年代CSV文件结构..然后当你阅读所有的数据转换为字符串[]你可以做一个while循环检查帐户名称是否相等..当他们不..然后做你的计算和设置新的帐户名称等于前面例如帐户名称不等于第一次读取初始化账户名= to'string.Empty'读取第一个名字..并发送账户变量=第一个值,这将是'Smith'下一个读取或字符串[] 0将等于史密斯。 ..第三不会 – MethodMan

+0

然后你做你的计算...等......有很多方法来做到这一点..如果你画出来,你会看到它是多么容易..也可以总结一个值string []使用'Linq和Skip()'函数 – MethodMan

+1

我想创建一个类来模仿CSV文件。但由于某种原因,认为会有一种更简单的方法。所以我会继续做下去。谢谢你确认我的怀疑。 –

回答

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); 
     }