Reputation: 3
I currently am trying to analyze a CSV file then output only items that meet a certain criteria. I am using the CSVHelper library.
So far I am able to import the file, and I am able to export it, ...sort of.
For some reason it is tripling the number of entries. As in, it goes through the values once successfully, then outputs all the values twice in a row. Like:
A
B
C
D
A
A
B
B
C
C
D
D
So that is question 1. why?
Question 2: how do I get it to filter and only output data that meets the criteria? Column 2 is age, and the age must be 62 or older.
Below is my code thus far:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Diagnostics;
using CsvHelper;
using System.Collections;
namespace firstdraft
{
class Program
{
public String Name { get; set; }
public String Age { get; set; }
private static void Main(string[] args)
{
using (var sr = new StreamReader(@"people.csv"))
{
using (var sw = new StreamWriter(@"results.csv"))
{
var reader = new CsvReader(sr);
var writer = new CsvWriter(sw);
IEnumerable<Program> records = reader.GetRecords<Program>().ToList();
writer.WriteRecords(records);
foreach (Program record in records)
{
writer.WriteRecord(record);
writer.WriteField(record.Name);
writer.WriteField(record.Age);
writer.NextRecord();
}
}
}
}
}
}
Upvotes: 0
Views: 205
Reputation: 1585
You're writing the records 3 times. First, writing them all (A B C D):
writer.WriteRecords(records);
Next, you're writing each record as you iterate through them:
writer.WriteRecord(record);
And then you're writing it again, column by column:
writer.WriteField(record.Name);
writer.WriteField(record.Age);
writer.NextRecord();
What were you trying to achieve there?
For filtering, you might want to do something like this via LINQ:
IEnumerable<Program> records = reader.GetRecords<Program>().Where(r => r.Age >= 62).ToList();
writer.WriteRecords(records);
// No futher code
Assuming that works a little more as intended?
Upvotes: 1