Recently I had an interview question about extracting records that matched certain criteria from a 2D List of strings. The premise was a CSV file was parsed into a List<List<string>>
, and I need to filter them based on a record type (only keep "SALE" and "REFUND") and sort them by the date and time found in the record.
The Main function, I was unable to edit besides adding more records to, simply called the function I was to write with the list of sample records, then wrote the records returned by my function to standard output.
/* Each record has 4 elements. 1- date in day month year format 2- time in hour : minute format with a 24 hour clock 3- record type 4- dollar value */ public class Program { public static void Main() { var record1 = new List<string>() { "30-01-2012", "14:50", "SALE", "10" }; var record2 = new List<string>() { "30-01-2015", "14:50", "REFUND", "10" }; var record3 = new List<string>() { "23-01-2012", "14:50", "CANCEL", "0" }; var record4 = new List<string>() { "30-01-2012", "14:51", "SALE", "10" }; var records = new List<List<string>>() { record1, record2, record3, record4 }; var results = RecordExtractor.Extract(records); foreach(var result in results) { Console.WriteLine(String.Join(",", result)); } } }
I was able to come up with a solution for this challenge, but am unsure how efficient it is for larger sets of data. In specific, I'm not sure if the string comparison or the ordering by date could be done in a faster way. The function I created is as follows:
public static class RecordExtractor { private static readonly string _sale = "SALE"; private static readonly string _refund = "REFUND"; public static List<List<string>> Extract(List<List<string>> records) { var filteredRecords = new List<List<string>> (); foreach(var record in records) { var recordType = record[2]; if(string.Equals(recordType, _sale, StringComparison.InvariantCultureIgnoreCase) || string.Equals(recordType, _refund, StringComparison.InvariantCultureIgnoreCase)) { filteredRecords.Add(record); } } var orderedOutput = filteredRecords.OrderBy(x => { DateTime.TryParseExact($"{x[0]} {x[1]}", "dd-MM-yyyy HH:mm", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out var dt); return dt; }); return orderedOutput.ToList(); } }
List<List<string>>
. If I were to gauge a developer's skills, I would pass them the CSV file and let them read from it. Whether they read the file in one big gulp or read in sections would tell me a lot. Also, I would hope to see someIEnumerable
usage, or evenIList
rather than justList
.\$\endgroup\$