Simple example: Creating jagged arrays using LINQ

apegram 3 Tallied Votes 684 Views Share
int[][] jaggedArray = (from line in File.ReadAllLines(fileName).Skip(1)
                           select
                           (from item in line.Split('\t').Skip(1)
                            select int.Parse(item)).ToArray()).ToArray();

This is a crazy example. It was sparked by what is probably a homework thread on another forum here, but it is basically reading in a tab-delimitted text file, stripping out the first row and column (as they contain header information), and spitting out a jagged array of integers as the final product. The crazy part? It's a single statement! All that functionality, 1 semi-colon.

The crazier fact is that the above is just syntactic sugar for what the compiler will first translate the code to, as the compiler will take this snippet and get rid of the query expression and transform the statement into one using extension methods and lambda expressions instead. Something probably more like the below:

int[][] jaggedArray = File.ReadAllLines(fileName).Skip(1).Select(line => line.Split('\t').Skip(1).Select(item => int.Parse(item)).ToArray()).ToArray();

The sad-to-admit part is that the version immediately above came to me within moments of seeing the original problem, but the snippet at the top using the cleaner query expression syntax took way too many tries for me to get the result I desired. Way too many tries.

Anyway, I thought I would post it because (a) it's cool and (b) did I tell you it took way too many tries to get the right query expression syntax?

Here's a matrix format for you to test it against if you desire.

A	B	C	D	E
A	1	2	3	4	5
B	6	7	8	9	10
C	11	12	13	14	15
D	16	17	18	19	20
E	21	22	23	24	25

I encourage you all to explore the many facets of .NET 3.5 such as query expressions, lambdas, extension methods, anonymous types, and so on. After all, .NET 4 is releasing in less than a month! There will be even more to explore.

** Bonus if anyone can craft a way to turn the jagged array into a 2D array by using LINQ. It can obviously be done by iterating over the jagged array once it has been created, but a LINQ version might be fun to try. (If it is even possible!)

kvprajapati commented: Linq++ +8
ddanbe commented: Cool! +6
int[][] jaggedArray = (from line in File.ReadAllLines(fileName).Skip(1)
                           select
                           (from item in line.Split('\t').Skip(1)
                            select int.Parse(item)).ToArray()).ToArray();
ddanbe 2,724 Professional Procrastinator Featured Poster

If you have more LINQ snippets, please don't hesitate to post them!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.