Created
June 1, 2022 17:42
-
-
Save JerryNixon/de3aeaa1f8b73575240418891e3a746c to your computer and use it in GitHub Desktop.
Read a CSV
This file contains hidden or 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 Microsoft.Azure.WebJobs; | |
| using System; | |
| using System.Collections.Generic; | |
| using System.Linq; | |
| public static class Csv | |
| { | |
| public static IEnumerable<T> Read<T>(ExecutionContext context, string file) where T : new() | |
| { | |
| var path = System.IO.Path.Combine(context.FunctionDirectory, file); | |
| var csv = System.IO.File.ReadAllText(path); | |
| return Csv.Parse<T>(csv, strict: false); | |
| } | |
| public static IEnumerable<T> Parse<T>(string csv, bool strict) where T : new() | |
| { | |
| var lines = csv.Split(Environment.NewLine); | |
| var columns = lines.First().Split(",").Select((x, i) => new { Index = i, Name = x }); | |
| var rows = lines.Skip(1) | |
| .Where(x => x is not null && x != String.Empty) | |
| .Select((x, i) => new { Index = i, Cells = x.Split(",") }); | |
| foreach (var row in rows) | |
| { | |
| if (!Equals(row.Cells.Count(), columns.Count())) | |
| { | |
| var message = $"Row does not have same number of columns as header: row index {row.Index}."; | |
| throw new IndexOutOfRangeException(message); | |
| } | |
| var item = new T(); | |
| foreach (var column in columns) | |
| { | |
| var name = column.Name.Replace(" ", string.Empty); | |
| var properties = typeof(T).GetProperties(); | |
| var property = properties.FirstOrDefault(x => x.Name.ToLower() == name.ToLower()); | |
| if (property is null) | |
| { | |
| if (!strict) | |
| { | |
| continue; | |
| } | |
| var message = $"Type is missing property in header: type {typeof(T)}, property name: {name}."; | |
| throw new MissingMemberException(message); | |
| } | |
| var cell = row.Cells[column.Index].Trim('"'); | |
| property.SetValue(item, cell); | |
| } | |
| yield return item; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment