Skip to content

Instantly share code, notes, and snippets.

@Sheepings
Last active November 27, 2019 00:31
Show Gist options
  • Save Sheepings/6d36bb1a487c5ca019f620b4d7af0aac to your computer and use it in GitHub Desktop.
Save Sheepings/6d36bb1a487c5ca019f620b4d7af0aac to your computer and use it in GitHub Desktop.
Using the textfieldparser to read a files contents to a list string array
public static readonly string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "mytext.txt");
public static List<string[]> IEnum = new List<string[]>();
private void Button1_Click(object sender, EventArgs e)
{
using (FileStream reader = File.OpenRead(path))
using (TextFieldParser iParse = new TextFieldParser(reader))
{
iParse.Delimiters = new[] { "," }; iParse.HasFieldsEnclosedInQuotes = true;
do
IEnum.Add(iParse.ReadFields());
while (!iParse.EndOfData);
}
}
private void button2_Click(object sender, EventArgs e)
{
foreach (var (firstName, secondName)
in from string[] line in IEnum
let firstName = line[0]
let secondName = line[1]
let genderType = line[2]
let emailAddress = line[3]
let personalAddress = line[4]
let personalDOB = line[5]
select (firstName, secondName))
/* To get more variables, you need to extend Linq to iterate over and select the additional's */
{
Console.WriteLine($"Persons first name is : {firstName}");
var fullName = string.Concat(firstName, string.Empty.PadRight(1), secondName);
Console.WriteLine($"Persons Full Name is : {string.Concat(firstName, string.Empty.PadRight(1), secondName)}");
}
}
private void button3_Click(object sender, EventArgs e)
{
for (int i = 0; i < IEnum.Count; i++)
{
var firstName = IEnum[i][0];
var secondName = IEnum[i][1];
var genderTyple = IEnum[i][2];
var emailAddress = IEnum[i][3];
Console.WriteLine(firstName);
/* [i] iterates the IEnum and is self-incremental, while [0] (if changed) will give you a different result, first name [0] second name be [1] etc */
}
}
/* File contents was as follows :
Petras, Petraitis, Vyras, petras.p1 @dope.com, Nice g. 14, 1992-12-01
Petryte, Petraite, Moteris, petryte.p2 @dope.com, Sad g. 14, 2000-06-01
Antanas, Antanaitis, Vyras, antanas.a1 @dope.com, Cool g. 19, 1988-06-02
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment