M
M
Matvey Kremnin2016-11-08 15:31:28
.NET
Matvey Kremnin, 2016-11-08 15:31:28

How to sort a 2D array by sum of column elements?

I can not understand the implementation itself ..
I would be grateful for the help.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DoubleArray
{
    class Program
    {
        static void Main(string[] args)
        {

            int firstNmb = 0;
            int secondNmb = 0;

            Console.Write("Write 1-st number: ");
            firstNmb = Convert.ToInt32(Console.ReadLine());

            Console.Write("Write 2-nd number: ");
            secondNmb = Convert.ToInt32(Console.ReadLine());

            int[,] doubleArr = new int[firstNmb, secondNmb];
            Random ran = new Random();

            for (int i = 0; i < firstNmb; i++)
            {
                for (int j = 0; j < secondNmb; j++)
                {
                    doubleArr[i, j] = ran.Next(-100, 100);
                    Console.Write("{0}\t", doubleArr[i, j]);
                }
                Console.WriteLine();
            }
            Console.ReadLine();
        }
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrew, 2016-11-11
@impwx

LINQ comes to the rescue:

var random = new Random();

// размеры массива, в качестве примера взяты константы
var columns = 10;
var rows = 5;

// создаем данные
var data = new int[rows][];
for(var row = 0; row < rows; row++)
{
    data[row] = new int[columns];
    for(var column = 0; column < columns; column++)
        data[row][column] = random.NextInt(-100, 100);   
}

// сортируем данные
var sorted = data.OrderBy(x => x.Sum()).ToArray();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question