List seems to be acting weird for me, I'm trying to convert an IEnumberable enumberableRecords into a list, but it isn't working out for me.
Each record in enumberableRecords is a row of data from a csv file, for reference.
Basically, the first write command outputs the data correctly all 866 times, but the second and third write commands are the same as the first, and the fourth only outputs the last line of the csv, 866 times.
You would expect the second write command to be the first row of the csv, which it isn't, the third is correct, but I suspect this is by happenstance rather than anything else, and the fourth you would suspect to match the first, but it rather just writes the last line of the csv.
I've also tried using List<SettlementRecord> records = enumberableRecords.ToList(); instead, but the same issue occurred.
List<SettlementRecord> records = new List<SettlementRecord>(); foreach(SettlementRecord record in enumerableRecords) { Console.WriteLine(record.id); records.Add(record); Console.WriteLine(records.First().id); Console.WriteLine(records.Last().id); } foreach (SettlementRecord record in records) { Console.WriteLine(record.id); } There probably is some stupid solution to this that I'm missing, but... I can't see it. Any help would be appreciated.
Edit: Here's the... Minimum thingy. Uses the CsvHelper package. Also you need a csv file Sample.csv in the root directory. I'll add an example to the end.
using System; using System.Globalization; using System.IO; using System.Collections.Generic; using System.Linq; using CsvHelper; namespace Example { class Program { static void Main(string[] args) { StreamReader csvReader = new StreamReader(AppDomain.CurrentDomain.BaseDirectory + "Sample.csv"); CsvReader csv = new CsvReader(csvReader, CultureInfo.InvariantCulture); SettlementRecord settlementRecord = new SettlementRecord(); IEnumerable<SettlementRecord> enumerableRecords = csv.EnumerateRecords(settlementRecord); List<SettlementRecord> records = new List<SettlementRecord>(); foreach (SettlementRecord record in enumerableRecords) { Console.WriteLine(record.id); records.Add(record); Console.WriteLine(records.First().id); Console.WriteLine(records.Last().id); } foreach (SettlementRecord record in records) { Console.WriteLine(record.id); } } class SettlementRecord { public string id { get; set; } } } } Here's an example Sample.csv file
id a b c d e f g https://stackoverflow.com/questions/65546638/list-add-and-ienumberable-tolist-seemingly-resulting-in-a-list-with-incorr January 03, 2021 at 12:29PM
没有评论:
发表评论