Forked from Sheepings/GetPersonFromTextFile.cs
Last active
November 12, 2019 02:22
-
-
Save azureskydiver/537940e26f7b1d2303dad1801a36d0eb to your computer and use it in GitHub Desktop.
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
public partial class Form1 : Form | |
{ | |
static readonly string _defaultPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "mytext.txt"); | |
readonly PersonsRepository _repository; | |
public Form1() | |
: this(new PersonsRepository(_defaultPath)) | |
{ | |
} | |
public Form1(PersonsRepository repository) | |
{ | |
_repository = repository; | |
InitializeComponent(); | |
} | |
void Button1_Click(object sender, EventArgs e) | |
{ | |
_repository.Load(); | |
} | |
void button2_Click(object sender, EventArgs e) | |
{ | |
var personFound = _repository.FindPerson("Antanas"); | |
/* Do things with the persons info */ | |
if (personFound != null) | |
MessageBox.Show($"Persons Address is : {personFound.Address}"); | |
else | |
MessageBox.Show("No person found"); | |
} | |
} | |
class PersonsRepository | |
{ | |
Lazy<List<Person>> _persons; | |
public IEnumerable<Person> Persons => _persons.Value; | |
public PersonsRepository(string path) | |
=> _persons = new Lazy<List<Person>>(() => ReadAllPersons(path)); | |
List<Person> ReadAllPersons(string path) | |
{ | |
var list = new List<Person>(); | |
using (TextFieldParser parser = new TextFieldParser(path)) | |
{ | |
parser.SetDelimiters(","); | |
while (!parser.EndOfData) | |
list.Add(ParseLine(parser)); | |
} | |
return list; | |
} | |
Person ParseLine(TextFieldParser parser) | |
{ | |
string[] fields = parser.ReadFields(); | |
return new Person() | |
{ | |
FirstName = fields[0], | |
LastName = fields[1], | |
Gender = fields[2], | |
Email = new MailAddress(fields[3]), | |
Address = fields[4], | |
DateOfBirth = DateTime.Parse(fields[5]) | |
}; | |
} | |
public void Load() | |
=> Persons.Count(); // count objects to force loading into memory | |
public Person FindPersonByFirstName(string firstName) | |
=> Persons.FirstOrDefault(p => p.FirstName == firstName); | |
} | |
class Person | |
{ | |
public string FirstName { get; set; } | |
public string LastName { get; set; } | |
public string Gender { get; set; } | |
public MailAddress Email { get; set; } | |
public string Address { get; set; } | |
public DateTime DateOfBirth { get; set; } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment