3

I'd like to archieve behaviour similar to Pythons' groupby.

[1, 1, 2, 1].GroupBy() => [[1, 1], [2], [1]]
0

2 Answers 2

1

I think this is what you're looking for:

var data = new int[] { 1, 1, 2, 1 };
var results = Enumerable.Range(0, data.Count ())
    .Where (i => i == 0 || data.ElementAt(i - 1) != data.ElementAt(i))
    .Select (i => new
                  {
                  //Key = data.ElementAt(i),
                  Group = Enumerable.Repeat(
                     data.ElementAt(i), 
                     data.Skip(i).TakeWhile (d => d == data.ElementAt(i)).Count ())
                  }
             );

Here's an example of it running and the results: http://ideone.com/NJGQB

1

Here's a lazy, generic extension method that does what you want.


Code:

public static IEnumerable<IEnumerable<T>> MyGroupBy<T>(this IEnumerable<T> source)
{
    using(var enumerator = source.GetEnumerator())
    {
        var currentgroup = new List<T>();
        while (enumerator.MoveNext())
        {
            if (!currentgroup.Any() || currentgroup[0].Equals(enumerator.Current))
                currentgroup.Add(enumerator.Current);
            else
            {
                yield return currentgroup.AsReadOnly();                 
                currentgroup = new List<T>() { enumerator.Current };
            }
        }
        yield return currentgroup.AsReadOnly();
    }
}

Test:

void Main()
{
    var data = new int[] { 1, 1, 2, 1 };

    foreach(var g in data.MyGroupBy())
        Console.WriteLine(String.Join(", ", g));
}

Output:

1, 1
2
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.