How to group consecutive similar items of a collection?

后端 未结 5 846
忘了有多久
忘了有多久 2020-12-06 23:06

Consider the following collection.

  • True
  • False
  • False
  • False
  • True
  • True
  • False
  • False

I

5条回答
  •  囚心锁ツ
    2020-12-06 23:25

    While the code in the accepted answer meets the needs of the original question, it will fall over when handling IEnumerables of more complex objects (since the predicate will tend to throw an exception when comparing the last item in the enumerable with the "next" item [which, by definition, will always be null]).

    This version handles more complex objects:

       public static IEnumerable> GroupConsecutive(this IEnumerable set, Func predicate)
        {
            var i = 0;
            var k = 0;
            var ranges = from e in set
                         let idx = ++i
                         let next = set.ElementAtOrDefault(idx)
                         let key = next == null ? k : (predicate(e, next)) ? k : k++
                         group e by key into g
                         select g;
            return ranges;
        } 
    

提交回复
热议问题