// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace E { public class Data { public int Id { get; set; } public string Text { get; set; } } public class CSVReader { private StreamReader stream; private char fieldsep; private char strquote; private char esc; public CSVReader(StreamReader stream, char fieldsep, char strquote, char esc = '\u0000') { this.stream = stream; this.fieldsep = fieldsep; this.strquote = strquote; this.esc = esc; } public List ReadLine() { string line = stream.ReadLine(); if(line == null) return null; List res = new List(); bool inq = false; bool skip = false; StringBuilder tmp = new StringBuilder(""); for(int i = 0; i < line.Length; i++) { char c = line[i]; if(skip) { tmp.Append(c); skip = false; } else if((c == fieldsep) && !inq) { res.Add(tmp.ToString()); tmp = new StringBuilder(""); } else if((c == esc) && (i < line.Length - 1) && (line[i + 1] == strquote)) { skip = true; } else if((c == strquote) && ((tmp.Length == 0) || inq)) { inq = !inq; } else { tmp.Append(c); } } res.Add(tmp.ToString()); return res; } public T ReadLine(params Action[] asgn) where T : class, new() { List raw = ReadLine(); if(raw == null) return null; T o = new T(); for(int i = 0; i < asgn.Length; i++) { asgn[i](raw[i], o); } return o; } public List ReadAllLines(params Action[] asgn) where T : class, new() { List res = new List(); T o; while((o = ReadLine(asgn)) != null) { res.Add(o); } return res; } } public class Program { public static void Main(string[] args) { using(StreamReader sr = new StreamReader(@"C:\work\data.csv")) { CSVReader csv = new CSVReader(sr, ',', '"', '"'); List data = csv.ReadAllLines( (s,o) => { o.Id = int.Parse(s); }, (s,o) => { o.Text = s; }); /* foreach(Data o in data) { Console.WriteLine("{0},\"{1}\"", o.Id, o.Text); } */ // find the text for id 2 Console.WriteLine(data.Find(r => r.Id == 2).Text); // find all id's where text contains a 'm' or 'M' foreach(Data o in data.Where(r => r.Text.ToLower().Contains('m'))) { Console.WriteLine(o.Id); } // find the text for id 2 Console.WriteLine(data.Find(r => r.Id == 5).Text); } } } }