Flattening a Jagged Array with LINQ
- by PSteele
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: .NET,LINQ,Jagged Array