fork download
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4.  
  5. class Program
  6. {
  7. static void Main(string[] args)
  8. {
  9. //Test with classes
  10. string[] classesList1 = new[] {"a", "b", "c"};
  11. string[] classesList2 = new[] { "1", "2", "3" };
  12. List<string[]> classesListCombined = new List<string[]> { classesList1, classesList2 };
  13.  
  14. Console.WriteLine("classesList1: {0}", String.Join(",", classesList1.SelectManyRecusive<string>()));
  15. Console.WriteLine("classesListCombined: {0}", String.Join(",", classesListCombined.SelectManyRecusive<string>()));
  16.  
  17. //Test with structs
  18. int[] structList1 = new[] { 1, 2, 3 };
  19. int[] structList2 = new[] { 4, 5, 6 };
  20. List<int[]> structListCombined = new List<int[]> { structList1, structList2 };
  21.  
  22.  
  23. Console.WriteLine("structList1: {0}", String.Join(",", structList1.SelectManyRecusive<int>()));
  24. Console.WriteLine("structListCombined: {0}", String.Join(",", structListCombined.SelectManyRecusive<int>()));
  25.  
  26. //Test tripple nesting
  27.  
  28. var nest1 = new[] {1, 2, 3};
  29. var nest2 = new[] { 4, 5, 6 };
  30. var nest3 = new[] { 7, 8, 9 };
  31. var nest4 = new[] {10, 11, 12};
  32.  
  33. var layer1 = new[] {nest1, nest2};
  34. var layer2 = new[] {nest3, nest4};
  35. var top = new[] {layer1, layer2};
  36.  
  37.  
  38. Console.WriteLine("top: {0}", String.Join(",", top.SelectManyRecusive<int>()));
  39.  
  40. Console.ReadLine();
  41.  
  42. }
  43. }
  44.  
  45. internal static class ExtensionMethods
  46. {
  47. public static IEnumerable<T> SelectManyRecusive<T>(this IEnumerable enumerable)
  48. {
  49. foreach (var item in enumerable)
  50. {
  51. var castEnumerable = item as IEnumerable;
  52. if (castEnumerable != null
  53. && ((typeof(T) != typeof(string)) || !(castEnumerable is string))) //Don't split string to char if string is our target
  54. {
  55. foreach (var inner in SelectManyRecusive<T>(castEnumerable))
  56. {
  57. yield return inner;
  58. }
  59. }
  60. else
  61. {
  62. if (item is T)
  63. {
  64. yield return (T) item;
  65. }
  66. }
  67. }
  68. }
  69. }
Success #stdin #stdout 0.05s 24384KB
stdin
Standard input is empty
stdout
classesList1: a,b,c
classesListCombined: a,b,c,1,2,3
structList1: 1,2,3
structListCombined: 1,2,3,4,5,6
top: 1,2,3,4,5,6,7,8,9,10,11,12