markzzz
markzzz

Reputation: 47945

How can I create a multi-type matrix?

I have these data :

4  pippo pluto paperino
10 marco paolo roberto
2  hello cruel world

and I'd like to store these data into a multi-type matrix myMatrix. (First field is an integer, the rest are strings).

So, if I type myMatrix[1][2] I must get paolo. How can I do it on C#?

Upvotes: 2

Views: 2142

Answers (5)

Oded
Oded

Reputation: 499062

You can't use arrays to store different types of objects that are not part of the same inheritance chain.

an object[][] will work, but you will not have type safety and need to cast to the target type.

You can use Tuple<int,string,string,string>[] (introduced in .NET 4.0), though your own simple type would be a more readable option.

Instead of using arrays, you could use one of the collection types - for example List<T>, where the generic type is a tuple or your custom type.

You really need to think about the usage this collection will be put into before you can select a suitable data structure.

Upvotes: 4

Mohamad Alhamoud
Mohamad Alhamoud

Reputation: 4929

Dictionary<int, string[]> is the simplest way as I think.

More about Dictionary type can be found here

Upvotes: 2

ken2k
ken2k

Reputation: 48985

The best way is to create a class that represent your data, with 4 fields (integer, string, string, string).

public class MyClass
{
    public int Param1 { get; set; }
    public string Param2 { get; set; }
    public string Param3 { get; set; }
    public string Param4 { get; set; }
}

Then simply use a List<MyClass> to store your data. To get Paolo you'll need to use List[1].Param2 (also name your parameters with meaningful names).

Upvotes: 2

snurre
snurre

Reputation: 3105

Tuple<int, string, string, string>[]
object[][]
Dictionary<int, string[]>

Upvotes: 4

Samich
Samich

Reputation: 30125

You can use Dictionary<int, string[]> to get such effect:

Dictionary<int, string[]> myMatrix = new Dictionary<int, string[]>();
myMatrix.Add(4, new[] { "pippo", "pluto", "paperino" });
...


//get

myMatrix[4][1] == "pluto"

Upvotes: 2

Related Questions