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