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






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: