-1

Hi everybody I have an array with 1 to 100 number and I want to group it to four group that each group have 25 number. How can i do it. Thanks

 static void Main(string[] args)
        {
            int[] array = new int[101];
            for (int i = 1; i <= 100; i++)
            {
                array[i] = i; Console.WriteLine(array[i]);

            }
            var s = array.GroupBy(x => array.Length % 25).Select(d => new { k = d.Key, v = d.OrderBy(f => f) });
            foreach (var item in s)
            {
                Console.WriteLine($"{item.k}");
                foreach (var item2 in item.v)
                {
                    Console.WriteLine($"\t{item2}");
                }
                Console.WriteLine("------------");
            }`enter code here`
adelehasadi
  • 79
  • 1
  • 1
  • 3

1 Answers1

2

Your question is vague; there're many ways to group by the array:

int[] array = Enumerable
  .Range(1, 100)
  .ToArray();

Possible groupings (by index):

int[][] result = array
  .Select((item, index) => new {
     item = item,
     index = index })  
  .GroupBy(chunk => chunk.index % 4)
  .Select(chunk => chunk
     .Select(x => x.item)
     .ToArray())
  .ToArray();  

Or

int[][] result = array
  .Select((item, index) => new {
     item = item,
     index = index })  
  .GroupBy(chunk => chunk.index / 25)
  .Select(chunk => chunk
     .Select(x => x.item)
     .ToArray())
  .ToArray();  

Or grouping by value

int[][] result = array
  .GroupBy(item => item % 4)
  .Select(chunk => chunk
     .ToArray())
  .ToArray();

To print out the result (and test grouping) use string.Join:

string report = string.Join(Environment.NewLine, result
  .Select(line => string.Join(" ", line
     .Select(item => string.Format("{0,3}", item)))));

Console.Write(report);
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215