fork(1) download
  1. using System;
  2. using System.Globalization;
  3. using System.Linq;
  4. using System.Collections.Generic;
  5.  
  6. public class Test
  7. {
  8. public static void Main()
  9. {
  10. var words = new List<string>{"golf", "hip", "hop", "hotel", "grass", "world", "wee"};
  11. IEnumerable<string> lastWordOfConsecutiveFirstCharGroups = words
  12. .GroupAdjacent(str => str[0])
  13. .Select(g => g.Last());
  14. Console.WriteLine(string.Join(",",lastWordOfConsecutiveFirstCharGroups.ToArray()));
  15.  
  16. words=new List<string>{"apples", "armies", "black", "beer", "bastion", "cat", "cart", "able", "art", "bark"};
  17. lastWordOfConsecutiveFirstCharGroups = words
  18. .GroupAdjacent(str => str[0])
  19. .Select(g => g.Last());
  20. Console.WriteLine(string.Join(",",lastWordOfConsecutiveFirstCharGroups.ToArray()));
  21. }
  22. }
  23.  
  24. public static class Extensions
  25. {
  26. public static IEnumerable<IGrouping<TKey, TSource>> GroupAdjacent<TSource, TKey>(
  27. this IEnumerable<TSource> source,
  28. Func<TSource, TKey> keySelector)
  29. {
  30. TKey last = default(TKey);
  31. bool haveLast = false;
  32. List<TSource> list = new List<TSource>();
  33. foreach (TSource s in source)
  34. {
  35. TKey k = keySelector(s);
  36. if (haveLast)
  37. {
  38. if (!k.Equals(last))
  39. {
  40. yield return new GroupOfAdjacent<TSource, TKey>(list, last);
  41. list = new List<TSource>();
  42. list.Add(s);
  43. last = k;
  44. }
  45. else
  46. {
  47. list.Add(s);
  48. last = k;
  49. }
  50. }
  51. else
  52. {
  53. list.Add(s);
  54. last = k;
  55. haveLast = true;
  56. }
  57. }
  58. if (haveLast)
  59. yield return new GroupOfAdjacent<TSource, TKey>(list, last);
  60. }
  61.  
  62. public class GroupOfAdjacent<TSource, TKey> : IEnumerable<TSource>, IGrouping<TKey, TSource>
  63. {
  64. public TKey Key { get; set; }
  65. private List<TSource> GroupList { get; set; }
  66. System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
  67. {
  68. return ((System.Collections.Generic.IEnumerable<TSource>)this).GetEnumerator();
  69. }
  70. System.Collections.Generic.IEnumerator<TSource> System.Collections.Generic.IEnumerable<TSource>.GetEnumerator()
  71. {
  72. foreach (var s in GroupList)
  73. yield return s;
  74. }
  75. public GroupOfAdjacent(List<TSource> source, TKey key)
  76. {
  77. GroupList = source;
  78. Key = key;
  79. }
  80. }
  81. }
Success #stdin #stdout 0.03s 33840KB
stdin
Standard input is empty
stdout
golf,hotel,grass,wee
armies,bastion,cart,art,bark