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



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: