blue piranha
blue piranha

Reputation: 3874

storing matrix in a c# dictionary

I understand that a C# dictionary is basically a key:value pair

Is there a way to store matrix in a c# dictionary.

That is, can the key be a combination of two values (row, column)

For example

1 3
4 7

[0][0]:1, [0][1]:3, [1][0]:4, [1][1]:7

Can a dictionary be constructed for this? If so, how would I parse its elements. Things are much easier if key is a single value.

Thanks.

Upvotes: 1

Views: 878

Answers (5)

Mike Dinescu
Mike Dinescu

Reputation: 55730

To answer your question directly: yes, you could store a matrix in a dictionary.

Dictionary<Tuple<int,int>, int> matrix;

But a much better way is to store a matrix as a 2-dimensional or jagged array.

int[,] matrix;    // 2-dmmensional
int[][] matrix;   // jagged

The only time an array may be inefficient is if the matrix is sparse (ie. has many missing values). In that case, you might consider using a Dictionary or maybe a List.

Upvotes: 3

pierroz
pierroz

Reputation: 7870

You could also store your matrix in a 2 dimensional array:

int[,] matrix = new int[2,2];
matrix[0,0] = 1;
matrix[0,1] = 3;
matrix[1,0] = 4;
matrix[1,1] = 7;

Upvotes: 2

cuongle
cuongle

Reputation: 75306

You can declare Dictionary using Tuple class to store matrix:

Dictionary<Tuple<int,int>, int>

Or even KeyValuePair:

Dictionary<KeyValuePair<int, int>, int>

But if you don't have any specific reason, you should use multi-dimensional array int[,]

Upvotes: 1

JerKimball
JerKimball

Reputation: 16904

As I commented, you can use a plain old multidimensional array, but since you asked:

var array = new int[,]
{
    {1,2,3},
    {4,5,6},
    {7,8,9},
};
var query = 
    from row in Enumerable.Range(0, array.GetUpperBound(0))
    from col in Enumerable.Range(0, array.GetUpperBound(1))
    select new KeyValuePair<Tuple<int,int>, int>(
                Tuple.Create(row,col), 
                array[row,col]);
var asDict = query.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

Upvotes: 0

Jake H
Jake H

Reputation: 1740

You could use a Tuple<int,int> (link) as the key, since the values need to be immutable to be accurate keys for a dictionary. The only thing that I would like to point out is that matrices tend to be used in situations where extracting values by row or by column, and you would not be able to do that if you stored them in this manner.

Have you considered using a library that defines matricies already? There are plenty of math libraries and helpers that do exactly that.

Upvotes: 3

Related Questions