Skip to content

Instantly share code, notes, and snippets.

@bryanhunter
Created June 13, 2012 23:00
Show Gist options
  • Save bryanhunter/2927055 to your computer and use it in GitHub Desktop.
Save bryanhunter/2927055 to your computer and use it in GitHub Desktop.
Tab-separated Value data loader
public static class TabSeparatedValueDataLoader
{
public static IEnumerable<T> ParseTsv<T>(this string rawTabDeleimetedData, Func<string[], T> mapper)
{
IEnumerable<string[]> data = rawTabDeleimetedData.Split(new[] {'\r', '\n'},
StringSplitOptions.RemoveEmptyEntries)
.Select(x => x.Split(new[] {'\t'}, StringSplitOptions.None));
return data.Select(mapper);
}
}
public struct ProductionLocation
{
public int LocationId { get; set; }
public string Name { get; set; }
public Decimal CostRate { get; set; }
public Decimal Availability { get; set; }
public DateTime ModifiedDate { get; set; }
}
[TestFixture]
public class TsvUsageExample
{
[Test]
public void Demo()
{
List<ProductionLocation> productionLocations =
GetRawData().ParseTsv(x => new ProductionLocation
{
LocationId = int.Parse(x[0]),
Name = x[1],
CostRate = Decimal.Parse(x[2]),
Availability = Decimal.Parse(x[3]),
ModifiedDate = DateTime.Parse(x[4])
}).ToList();
ProductionLocation location20 = productionLocations.Single(x => x.LocationId == 20);
Assert.AreEqual("Frame Welding", location20.Name);
}
private string GetRawData()
{
// Tab-separated values: http://en.wikipedia.org/wiki/Tab-separated_values
// The data below is copy-pasted from the output of the SQL query:
// SELECT * FROM AdventureWorks.Production.Location
return
@"1 Tool Crib 0.0000 0.00 6/1/1998 12:00:00 AM
2 Sheet Metal Racks 0.0000 0.00 6/1/1998 12:00:00 AM
3 Paint Shop 0.0000 0.00 6/1/1998 12:00:00 AM
4 Paint Storage 0.0000 0.00 6/1/1998 12:00:00 AM
5 Metal Storage 0.0000 0.00 6/1/1998 12:00:00 AM
6 Miscellaneous Storage 0.0000 0.00 6/1/1998 12:00:00 AM
7 Finished Goods Storage 0.0000 0.00 6/1/1998 12:00:00 AM
10 Frame Forming 22.5000 96.00 6/1/1998 12:00:00 AM
20 Frame Welding 25.0000 108.00 6/1/1998 12:00:00 AM
30 Debur and Polish 14.5000 120.00 6/1/1998 12:00:00 AM
40 Paint 15.7500 120.00 6/1/1998 12:00:00 AM
45 Specialized Paint 18.0000 80.00 6/1/1998 12:00:00 AM
50 Subassembly 12.2500 120.00 6/1/1998 12:00:00 AM
60 Final Assembly 12.2500 120.00 6/1/1998 12:00:00 AM";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment