Vassilis
Vassilis

Reputation: 828

How to read a line of a text file into an array using c# and then get element by index

I am trying to read the last line of a text file into an array so that I am able to get a specific element of the array by index, but I am having trouble doing this as 1 line in my text file has many elements that need to go into the array as opposed to there being 1 element per line, so for reference my text file line structure would be like so: element1,element2,element3... It is similar in structure to that of a csv file.

My code so far that is not working:

string lastline = System.IO.File.ReadLines(myfilepath).Last();
string[] id = new string[](lastline.Split(','));

Then after inserting the line to my array I would like to pull an element of the array by the index, for example I want to pull element2 from the array and assign it to var item2, but am not sure how to go about that.

Upvotes: 0

Views: 462

Answers (1)

Sami
Sami

Reputation: 2110

Not sure if I understood your question completely, but getting single string from a string array by index:

string lastline = System.IO.File.ReadLines(myfilepath).Last();
string[] id = lastline.Split(',');

//string result = id[index];
/* Better way */
string result = id.ElementAtOrDefault(index);

Where index is the zero-based index of the items. So, the first string's index would be 0, next 1 etc. Thanks to Steve for pointing out the error in creating the array and the hint to avoid IndexOutOfRangeException.
The method ElementAtOrDefault(index) will return the element at index, or if the index is out of range, return a default element, which in this case is an empty string.

Upvotes: 5

Related Questions