I need to read a file and put that data inside to different arrays.
My .txt file looks like:
w1;
1 2 3
w2;
3 4 5
w3;
4 5 6
I tried something like the following:
int[] w1 = new int [3];
int[] w2 = new int [3];
int[] w3 = new int [3];
string v = "w1:|w2:|w3:";
foreach (string line in File.ReadAllLines(@"D:\\Data.txt"))
{
string[] parts = Regex.Split(line, v);
I got that string but I have no idea how to cut every element of it to arrays showed above.
Your RegEx doesn't actually do anything, you already have an array with each line separated. What you want to do is just ignore the lines that aren't data:
Or, you could just assign given that you know the order:
Rather than parsing the file and putting the arrays into three hardcoded variables corresponding to hardcoded names
w1
,w2
andw3
, I would remove the hardcoding and parse the file into aDictionary<string, int[]>
like so:And you would use it as follows:
Which outputs:
Notes:
I parse the integer values using
NumberFormatInfo.InvariantInfo
to ensure consistency of parsing in all locales.I break the lines of the file into chunks of two by using a lightly modified version of the method from this answer to Split List into Sublists with LINQ by casperOne.
After breaking the file into chunks of pairs of lines, I trim the
;
from the first line in each pair and use that as the dictionary key. The second line in each pair gets parsed into an array of integer values.If the names
w1
,w2
and so on are not unique, you could deserialize instead into aLookup<string, int []>
by replacingToDictionary()
withToLookup()
.Rather than loading the entire file into memory upfront using
File.ReadAllLines()
, I enumerate though it sequentially usingFile.ReadLines()
. This should reduce memory usage without any additional complexity.Sample working .Net fiddle.