The following code shows what I want to do:
public static IEnumerable<IEnumerable<T>> DoIt<T>(this IEnumerable<T> that)
{
if (that == null)
throw new ArgumentNullException();
if (that.Count() > 1)
{
var result = new Collection<IEnumerable<T>>();
var collection = new Collection<T>();
collection.Add(that.ElementAt(0));
for (int i = 1; i < that.Count(); ++i)
{
if (!that.ElementAt(i).Equals(that.ElementAt(i - 1)))
{
result.Add(collection);
collection = new Collection<T>();
}
collection.Add(that.ElementAt(i));
}
result.Add(collection);
return result;
}
return new Collection<IEnumerable<T>>() { that };
}
I’m only using custom implementations like that one, if there is no appropriate implementation already existing. Is there any way to do the same with the standard framework?
There is no traditional way to do this with the standard framework. I do have a couple of issues with your solution though.
ElementAt(i)is very inefficient and can cause thethatcollection to be iterated many, many times. This can lead to performance issuesCountalso can be costly as it can cause a full enumeration ofthatyield returnstyle solution.Here’s an alternative solution