Skip to content

Instantly share code, notes, and snippets.

@JeffJacobson
Last active December 16, 2015 07:38
Show Gist options
  • Save JeffJacobson/5400212 to your computer and use it in GitHub Desktop.
Save JeffJacobson/5400212 to your computer and use it in GitHub Desktop.
Converts a Text Table file to Dictionaries.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Dict = System.Collections.Generic.Dictionary<string, object>;
/*
Licensed under the MIT license (http://opensource.org/licenses/MIT)
Copyright (c) 2013 Washington State Department of Transportation
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Wsdot.Data.TextTable
{
public static class TextTableExtensions
{
/// <summary>
/// Reads a CSV file and outputs a list of dictionaries, keyed by the field names of the table.
/// </summary>
/// <param name="reader">A text reader that is reading CSV data.</param>
/// <param name="separator">The character that separates column values.</param>
/// <param name="delimiter">The character that surrounds string data.</param>
/// <returns>
/// A list of dictionaries.
/// Each dictionary in the list corresponds to one row of data in the table.
/// Each dictionary contains a key for each column heading.
/// </returns>
/// <example><![CDATA[const string filename = "XYData.csv";
/// List<Dictionary<string, object>> dict;
/// using (var stream = File.OpenText(filename))
/// {
/// dict = stream.CsvToDictionaryList();
/// }]]>
/// </example>
public static List<Dict> CsvToDictionaryList(this TextReader reader, char separator = ',', char delimiter = '"',
TypeCode floatingPointType = TypeCode.Double)
{
string[] headers = null;
string line = reader.ReadLine();
var dictList = new List<Dict>();
while (line != null)
{
if (headers == null)
{
headers = line.Split(separator).Select(s => s.Trim(delimiter)).ToArray();
}
else
{
dictList.Add(ToDictionary(separator, delimiter, headers, line, floatingPointType));
}
line = reader.ReadLine();
}
return dictList;
}
private static Dict ToDictionary(char separator, char delimiter, IEnumerable<string> headers, string line,
TypeCode floatingPointType)
{
var dict = new Dict();
var row = line.Split(separator).ParseRow(delimiter, floatingPointType);
for (int i = 0, hl = headers.Count(), rl = row.Count(); i < hl && i < rl; i++)
{
dict.Add(headers.ElementAt(i), row.ElementAt(i));
}
return dict;
}
private static IEnumerable<object> ParseRow(this IEnumerable<string> csvRow, char delimiter,
TypeCode floatingPointType)
{
Regex stringRe = new Regex(string.Format(@"(?<={0})[^{0}]+(?={0})", Regex.Escape(delimiter.ToString())));
foreach (string item in csvRow)
{
var match = stringRe.Match(item);
if (match.Success)
{
yield return match.Value;
continue;
}
DateTime dt;
if (DateTime.TryParse(item, out dt))
{
yield return dt;
continue;
}
if (floatingPointType == TypeCode.Decimal)
{
decimal d;
if (decimal.TryParse(item, out d))
{
yield return d;
continue;
}
else
{
yield return null;
continue;
}
}
else if (floatingPointType == TypeCode.Double)
{
double d;
if (double.TryParse(item, out d))
{
yield return d;
continue;
}
else
{
yield return null;
continue;
}
}
else if (floatingPointType == TypeCode.Single)
{
float f;
if (float.TryParse(item, out f))
{
yield return f;
continue;
}
else
{
yield return null;
continue;
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment