Created
February 29, 2012 13:12
-
-
Save alexyork/1940750 to your computer and use it in GitHub Desktop.
Using LINQ to flatten a data structure v Old-Skool C# code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| private static void FlattenData() | |
| { | |
| var dictionary = new Dictionary<string, string[]> { | |
| { "Foo", new [] { "foo-1", "foo-2" }}, | |
| { "Bar", new [] { "bar-1", "bar-2" }} | |
| }; | |
| IEnumerable<string> flattenedData; | |
| // Using LINQ | |
| flattenedData = dictionary.Values.SelectMany(d => d).ToArray(); | |
| // Old-school way | |
| foreach (var key in dictionary.Keys) | |
| { | |
| var dataSubset = dictionary[key]; | |
| flattenedData = flattenedData.Concat(dataSubset); | |
| } | |
| // Old-school way (compact) | |
| foreach (var key in dictionary.Keys) | |
| flattenedData = flattenedData.Concat(dictionary[key]); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment