Using LINQ to Find the Sum of a MultiDimensional Array

Here’s how to the find the sum of a multidimensional array using LINQ. This array has 3 rows and 2 columns:

C#

using System;
using System.Linq;

class Program
{
static void Main(string[] args)
{
try
{
var myArray = new int[,]
{
{ 1, 2 },
{ 3, 4 },
{ 5, 6 }
};
var arrSum =
(from int val in myArray
select val)
.Sum();

Console.WriteLine(arrSum);
Console.ReadLine();
}
catch (Exception ex)
{
// handle ex
}
}
}

VB.NET

Imports System
Imports System.Linq

Friend Class Program
Shared Sub Main(ByVal args() As String)
Try
Dim
myArray = New Integer(, ) { { 1, 2 }, { 3, 4 }, { 5, 6 } }
Dim arrSum = ( _
From val As Integer In myArray _
Select val).Sum()

Console.WriteLine(arrSum)
Console.ReadLine()
Catch ex As Exception
' handle ex
End Try
End Sub
End Class

No comments:

Post a Comment