From 980f38ba033fe7343ff857fa1470ffb0bf4302d3 Mon Sep 17 00:00:00 2001 From: Jake Norbut Date: Wed, 18 Dec 2019 13:46:22 -0600 Subject: [PATCH] using OrderedDictionary to CSVs are output with a predictable column order --- src/client/spark_core/utils/CsvHelper.cs | 30 ++++++++++++++++++++---- 1 file changed, 26 insertions(+), 4 deletions(-) diff --git a/src/client/spark_core/utils/CsvHelper.cs b/src/client/spark_core/utils/CsvHelper.cs index afc1dbd90..2b4fdfbe9 100644 --- a/src/client/spark_core/utils/CsvHelper.cs +++ b/src/client/spark_core/utils/CsvHelper.cs @@ -1,22 +1,29 @@ using System; using System.IO; using System.Collections.Generic; +using System.Collections.Specialized; using System.Linq; using System.Reflection; namespace bts.utils.csv { public static class CsvHelper { - public static string ToCsv(this IEnumerable items, IEnumerable properties = null) where T : class { + public static string ToCsv(this IEnumerable items, OrderedDictionary properties = null) where T : class { var output = ""; var delimiter = ","; - properties = properties == null ? typeof(T).GetProperties() : properties; + if (properties == null) { + properties = new OrderedDictionary(); + foreach (var pi in typeof(T).GetProperties()) { + properties.Add(pi.Name, pi); + } + } using (var sw = new StringWriter()) { - var header = properties.Select(n => n.Name).Aggregate((first, second) => first + delimiter + second); + var dict_values = properties.Values.OfType(); + var header = dict_values.Select(n => n.Name).Aggregate((first, second) => first + delimiter + second); sw.WriteLine(header); foreach (var i in items) { - var row = properties.Select(x => x.GetValue(i, null)) + var row = dict_values.Select(x => x.GetValue(i, null)) .Select(x => x == null ? "null" : x.ToString()) .Aggregate((first, second) => first + delimiter + second); sw.WriteLine(row); @@ -26,5 +33,20 @@ namespace bts.utils.csv { return output; } + public static OrderedDictionary create_ordering_maintainer(Type t, string[] property_names_in_order) { + OrderedDictionary od = new OrderedDictionary(); + var props = t.GetProperties(); + foreach (var n in property_names_in_order) { + var query = props.Where(pi => pi.Name == n); + if (query.Any()) { + var property_info = query.First(); + if (!od.Contains(property_info)) { + od.Add(n, property_info); + } + } + } + return od; + } + } }