在读取不同类型输出的数据时对重复值求和

时间:2015-05-08 17:00:50

标签: c# asp.net streamwriter

我正在从stream读取5000行数据,如下所示,并将其存储在新的CSV文件中。

ProductCode |Name   | Type  | Size | Price
ABC | Shoe  | Trainers  | 3 | 3.99
ABC | Shoe  | Trainers  | 3 | 4.99
ABC | Shoe  | Trainers  | 4 | 5.99 
ABC | Shoe  | Heels | 4 | 3.99
ABC | Shoe  | Heels | 5 | 4.99
ABC | Shoe  | Heels | 3 | 5.99
...

我希望CSV有一行但价格相加,而不是重复条目: 例如。如果我想要一个仅包含ProductCode,Name和Type的csv文件,则忽略Size。我希望它看起来像这样:

ProductCode |Name   | Type  | Price
ABC | Shoe  | Trainers  | 14.97
ABC | Shoe  | Heels | 14.97

仅显示ProductCode,名称:

ProductCode |Name   | Price
ABC | Shoe  | 29.94

显示ProductCode,名称,大小,忽略类型:

ProductCode |Name   | Type  | Size | Price
ABC | Shoe  | 3 | 14.97
ABC | Shoe  | 4 | 9.98
ABC | Shoe  | 5 | 4.99

我将包含所有字段的每一行存储为Product并保留所有Product的列表:

public class Product
    {
        public string ProductCode { get; set; }
        public string Name { get; set; }
        public string Type { get; set; }
        public string Price { get; set; }
    }

然后根据使用csvOutputType的{​​{1}}将所需字段输出到csv中,这对于每个Parser都是不同的。

ConvertToOutputFormat

我的代码是:

public class CodeNameParser : Parser {
    public override string ConvertToOutputFormat(Product p) {
         return string.Format("{0},{1},{2}", p.ProductCode, p.ProductName, p.Price);
    }
}

我不想再次浏览5000行以删除重复项,但是在将其添加到csv文件之前,我想检查该条目是否已存在。我知道我可以对所需的字段进行分组,但由于我有3个不同的输出,因此我需要为需要分组的不同密钥编写相同的代码3次。

string fileName = Path.Combine(directory, string.Format("{0}.csv", name));            
switch (csvOutputType)
            {
                case (int)CodeName:
                    _parser = new CodeNameParser();
                    break;
                case (int)CodeType:
                    _parser = new CodeTypeParser();
                    break;
                case (int)CodeNameType:
                    _parser = new CodeNameTypeParser();
                    break;
}

var results = Parse(stream).ToList(); //Parse returns IEnumerable<Product>
if (results.Any())
            {
                using (var streamWriter = File.CreateText(fileName))
                {
                    //writes the header line out
                    streamWriter.WriteLine("{0},{1}", header, name);

                    results.ForEach(p => { streamWriter.WriteLine(_parser .ConvertToOutputFormat(p)); });
                    streamWriter.Flush();
                    streamWriter.Close();
                }

                Optional<string> newFileName = Optional.Of(SharpZipWrapper.ZipFile(fileName, RepositoryDirectory));
                //cleanup
                File.Delete(fileName);
                return newFileName;
            }

还有其他办法吗?

0 个答案:

没有答案