Here’s the code:
File.ReadLines(sourceFilePath).Select(line => line.Split('\t')).ToArray();
I get what’s going on up until the “Select” keyword. Can someone please break down what is going on in “line => line.Split…
My understanding is that we are going line by line through the text file and parsing and splitting a line of input text by tabs (since I know the text is tab-delimited). But, what exactly is going on with “line => line…”?
And I get at the end of the line of code the text is going into an Array. But when I debug and step through the code and use the locals window what is the name of the Array that contains what has been read? How do I see what is read into the Array?
This is saying, essentially, “For each line in the file, split the line on the tab character into an array of strings, then create an array of those arrays (such that each element in the returned array is an array)”
The
Selectfunction takes an Enumerable of something and applies a function to each item, producing 1 output value for each input value. In other programming languages this is called a Map or a Projection.The => indicates a lambda expression which is compiled into a delegate function. It takes an argument called “line”, whose type is inferred by the usage (because
ReadLinesreturns an IEnumerable of Strings,lineis of type String).The lambda’s body has an implied return type of the value resulting from the last call (the call to
Split). Thus, the line says “run this lambda on each line”.Finally, the call to
.ToArrayat the end (outside of the lambda) converts theIEnumerable<String[]>returned bySelectinto an array of arrays (String[][]).