Created
April 25, 2013 11:01
-
-
Save bobbychopra/5458978 to your computer and use it in GitHub Desktop.
Dynamic Reading Simple 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 System; | |
using System.Collections; | |
using System.Collections.Generic; | |
using System.Dynamic; | |
using System.Linq; | |
using System.IO; | |
using System.Threading.Tasks; | |
namespace TestTPL | |
{ | |
class MainClass | |
{ | |
public static void Main (string[] args) | |
{ | |
var text = @"A,B | |
1,2 | |
3,4"; | |
foreach (dynamic s in new DynamicCsv(text)) | |
{ | |
Console.WriteLine (int.Parse (s.A) + int.Parse (s.B)); | |
} | |
Console.ReadLine(); | |
} | |
} | |
public class DynamicCsv : DynamicObject, IEnumerable | |
{ | |
string[] headers = null; | |
List<DynamicRow> records = new List<DynamicRow>(); | |
public DynamicCsv(string text) | |
{ | |
using(var sr = new StringReader(text)) | |
{ | |
headers = sr.ReadLine().Split(','); | |
while(true) | |
{ | |
var line = sr.ReadLine (); | |
if (null == line) | |
break; | |
records.Add (new DynamicRow(headers, line)); | |
} | |
} | |
} | |
public IEnumerator GetEnumerator() | |
{ | |
return records.GetEnumerator(); | |
} | |
} | |
public class DynamicRow : DynamicObject | |
{ | |
Dictionary<string, object> dictionary | |
= new Dictionary<string, object>(); | |
public DynamicRow(string[] header, string record) | |
{ | |
for(var i=0; i < header.Length; i++) | |
dictionary.Add (header[i].ToLower(), record.Split(',')[i]); | |
} | |
public override bool TryGetMember( | |
GetMemberBinder binder, out object result) | |
{ | |
// Converting the property name to lowercase | |
// so that property names become case-insensitive. | |
string name = binder.Name.ToLower(); | |
// If the property name is found in a dictionary, | |
// set the result parameter to the property value and return true. | |
// Otherwise, return false. | |
return dictionary.TryGetValue(name, out result); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment