August 24, 2009

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



Giving me +1 tells me you liked this article! Thanks in advance


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP 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 has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

0 Responses to "Using LINQ to Find the Sum of a MultiDimensional Array"
 

Copyright © 2009-2013 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions