Flattening a Jagged Array with LINQ

Posted by PSteele on ASP.net Weblogs See other posts from ASP.net Weblogs or by PSteele
Published on Wed, 10 Mar 2010 02:01:58 GMT Indexed on 2010/03/11 17:20 UTC
Read the original article Hit count: 366

Filed under:
|

Today I had to flatten a jagged array.  In my case, it was a string[][] and I needed to make sure every single string contained in that jagged array was set to something (non-null and non-empty).  LINQ made the flattening very easy.  In fact, I ended up making a generic version that I could use to flatten any type of jagged array (assuming it's a T[][]):

private static IEnumerable<T> Flatten<T>(IEnumerable<T[]> data)
{
    return from r in data from c in r select c;
}

Then, checking to make sure the data was valid, was easy:

var flattened = Flatten(data);
bool isValid = !flattened.Any(s => String.IsNullOrEmpty(s));

You could even use method grouping and reduce the validation to:

bool isValid = !flattened.Any(String.IsNullOrEmpty);
Technorati Tags: ,,

© ASP.net Weblogs or respective owner

Related posts about .NET

Related posts about LINQ