fork download
  1. using System;
  2. using System.Linq;
  3. using System.Collections.Generic;
  4.  
  5. class Foo
  6. {
  7. public int A { get; set; }
  8. public int B { get; set; }
  9. }
  10.  
  11. public class GroupOfAdjacent<TSource, TKey> : IEnumerable<TSource>, IGrouping<TKey, TSource>
  12. {
  13. public TKey Key { get; set; }
  14. private List<TSource> GroupList { get; set; }
  15. System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
  16. {
  17. return ((System.Collections.Generic.IEnumerable<TSource>)this).GetEnumerator();
  18. }
  19. System.Collections.Generic.IEnumerator<TSource> System.Collections.Generic.IEnumerable<TSource>.GetEnumerator()
  20. {
  21. foreach (var s in GroupList)
  22. yield return s;
  23. }
  24. public GroupOfAdjacent(List<TSource> source, TKey key)
  25. {
  26. GroupList = source;
  27. Key = key;
  28. }
  29. }
  30. public static class LocalExtensions
  31. {
  32. public static IEnumerable<IGrouping<TKey, TSource>> GroupAdjacent<TSource, TKey>(
  33. this IEnumerable<TSource> source,
  34. Func<TSource, TKey> keySelector)
  35. {
  36. TKey last = default(TKey);
  37. bool haveLast = false;
  38. List<TSource> list = new List<TSource>();
  39. foreach (TSource s in source)
  40. {
  41. TKey k = keySelector(s);
  42. if (haveLast)
  43. {
  44. if (!k.Equals(last))
  45. {
  46. yield return new GroupOfAdjacent<TSource, TKey>(list, last);
  47. list = new List<TSource>();
  48. list.Add(s);
  49. last = k;
  50. }
  51. else
  52. {
  53. list.Add(s);
  54. last = k;
  55. }
  56. }
  57. else
  58. {
  59. list.Add(s);
  60. last = k;
  61. haveLast = true;
  62. }
  63. }
  64. if (haveLast)
  65. yield return new GroupOfAdjacent<TSource, TKey>(list, last);
  66. }
  67. }
  68.  
  69. public class Test
  70. {
  71. public static void Main()
  72. {
  73. var list = new System.Collections.Generic.List<Foo>(){
  74. new Foo(){ A = 1, B = 1 },
  75. new Foo(){ A = 1, B = 2 },
  76. new Foo(){ A = 2, B = 3 },
  77. new Foo(){ A = 2, B = 4 },
  78. new Foo(){ A = 1, B = 5 },
  79. new Foo(){ A = 3, B = 6 }
  80. };
  81.  
  82. var groups = list.GroupAdjacent(x => x.A);
  83.  
  84. foreach (var abGroup in groups)
  85. {
  86. int aKey = abGroup.Key;
  87. var bList = string.Join(",", abGroup.Select(x => x.B.ToString()).ToArray());
  88. Console.WriteLine("A = {0}, Bs = [ {1} ] ", aKey, bList);
  89. }
  90. }
  91. }
Success #stdin #stdout 0.04s 38064KB
stdin
Standard input is empty
stdout
A = 1, Bs = [ 1,2 ] 
A = 2, Bs = [ 3,4 ] 
A = 1, Bs = [ 5 ] 
A = 3, Bs = [ 6 ]