Last active
October 2, 2015 14:39
-
-
Save sakapon/39c810a682e46484708c to your computer and use it in GitHub Desktop.
ExpressionsSample / CsvFile
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.IO; | |
using System.Linq; | |
using System.Text; | |
namespace ExpressionsConsole | |
{ | |
public static class CsvFile | |
{ | |
public static IEnumerable<Dictionary<string, string>> ReadLines(string path, Encoding encoding = null) | |
{ | |
// Simple implementation. | |
var lines = File.ReadLines(path, encoding ?? Encoding.UTF8).Select(l => l.Split(',')); | |
string[] columnNames = null; | |
foreach (var line in lines) | |
{ | |
if (columnNames == null) | |
columnNames = line; | |
else | |
yield return columnNames.Zip(line, (c, v) => new { c, v }).ToDictionary(o => o.c, o => o.v); | |
} | |
} | |
public static IEnumerable<TEntity> ReadEntities<TEntity>(string path, EntityType<TEntity> entityType, Encoding encoding = null) | |
{ | |
if (entityType == null) throw new ArgumentNullException("entityType"); | |
var parameters = entityType.ConstructorInfo.GetParameters(); | |
return ReadLines(path, encoding) | |
.Select(d => parameters.Select(p => d[p.Name].To(p.ParameterType)).ToArray()) | |
.Select(p => entityType.CreateEntity(p)); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace ExpressionsConsole | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
CsvTest(); | |
} | |
static void CsvTest() | |
{ | |
var TaskItemType = EntityType.Create(new { Id = 0, Name = "", Rotation = DayOfWeek.Sunday, StartTime = TimeSpan.Zero }); | |
var query = CsvFile.ReadEntities("tasks.csv", TaskItemType) | |
.Where(o => o.Rotation == DayOfWeek.Monday) | |
.OrderBy(o => o.StartTime); | |
foreach (var item in query) | |
Console.WriteLine("{0}: {1}", item.StartTime, item.Name); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment