fork download
  1. using System;
  2. using System.Linq;
  3.  
  4. class Foo
  5. {
  6. public int A { get; set; }
  7. public int B { get; set; }
  8. }
  9.  
  10. public class Test
  11. {
  12. public static void Main()
  13. {
  14. var list = new System.Collections.Generic.List<Foo>(){
  15. new Foo(){ A = 1, B = 1 },
  16. new Foo(){ A = 1, B = 2 },
  17. new Foo(){ A = 2, B = 3 },
  18. new Foo(){ A = 2, B = 4 },
  19. new Foo(){ A = 1, B = 5 },
  20. new Foo(){ A = 3, B = 6 }
  21. };
  22.  
  23. var groups = list
  24. .Select((f, i) => new
  25. {
  26. Obj = f,
  27. Next = list.ElementAtOrDefault(i + 1),
  28. Prev = list.ElementAtOrDefault(i - 1)
  29. })
  30. .Select(x => new
  31. {
  32. A = x.Obj.A,
  33. x.Obj,
  34. Consecutive = (x.Next != null && x.Next.A == x.Obj.A)
  35. || (x.Prev != null && x.Prev.A == x.Obj.A)
  36. })
  37. .GroupBy(x => new { x.Consecutive, x.A });
  38.  
  39. foreach (var abGroup in groups)
  40. {
  41. int aKey = abGroup.Key.A;
  42. var bList = string.Join(",", abGroup.Select(x => x.Obj.B.ToString()).ToArray());
  43. Console.WriteLine("A = {0}, Bs = [ {1} ] ", aKey, bList);
  44. }
  45. }
  46. }
Success #stdin #stdout 0.05s 37320KB
stdin
Standard input is empty
stdout
A = 1, Bs = [ 1,2 ] 
A = 2, Bs = [ 3,4 ] 
A = 1, Bs = [ 5 ] 
A = 3, Bs = [ 6 ]