LINQ method for grouping a collection into subgroups with a given number of elements

Is there a LINQ method for grouping this set into subgroups with a specified number of elements, which means the Scala method grouped.
for example in Scala, List(89, 67, 34, 11, 34).grouped(2)gives List(List(89, 67), List(34, 11), List(34)).

If such a method does not exist, what will the LINQ method be?

+3
source share
3 answers

Yes, you can. But you can argue whether this is very ...

  Int64[] aValues = new Int64[] { 1, 2, 3, 4, 5, 6 };
  var result = aValues
          .Select( ( x, y ) => new KeyValuePair<Int64, Int32>( x, y ) )
          .GroupBy( x => x.Value / 2 )
          .Select( x => x.Select( y => y.Key ).ToList() ).ToList();

How it works:

x y , x - , y - . ( 2).

- 0/2 = 0, 1/2 = 0 .., . , .

, , .

+2

, .

public static class GroupingExtension
{
    public static IEnumerable<IEnumerable<T>> Grouped<T>(
        this IEnumerable<T> input,
        int groupCount)
    {
        if (input == null) throw new ArgumentException("input");
        if (groupCount < 1) throw new ArgumentException("groupCount");

        IEnumerator<T> e = input.GetEnumerator();

        while (true)
        {
            List<T> l = new List<T>();
            for (int n = 0; n < groupCount; ++n)
            {
                if (!e.MoveNext())
                {
                    if (n != 0)
                    {
                        yield return l;
                    }
                    yield break;
                }
                l.Add(e.Current);
            }
            yield return l;
        }
    }
}

:

List<int> l = new List<int>{89, 67, 34, 11, 34};
foreach (IEnumerable<int> group in l.Grouped(2)) {
    string s = string.Join(", ", group.Select(x => x.ToString()).ToArray());
    Console.WriteLine(s);
}

:

89, 67
34, 11
34
+2

Here is a website that seems to contain sample code that you need: http://www.chinhdo.com/20080515/chunking/

So what you can do is take this method and create an extension method.

Example extension method:

static class ListExtension
{
    public static List<List<T>> BreakIntoChunks<T>(this List<T> list, int chunkSize)
    {
        if (chunkSize <= 0)
        {
            throw new ArgumentException("chunkSize must be greater than 0.");
        }

        List<List<T>> retVal = new List<List<T>>();

        while (list.Count > 0)
        {
            int count = list.Count > chunkSize ? chunkSize : list.Count;
            retVal.Add(list.GetRange(0, count));
            list.RemoveRange(0, count);
        }

        return retVal;
    }
}
+2
source

Source: https://habr.com/ru/post/1753071/


All Articles