I need something similar to List<String, Int32, Int32>
. List only supports one type at a time, and Dictionary only two at a time. Is there a clean way to do something like the above (a multidimensional generic list/collection)?
Asked
Active
Viewed 6,812 times
7

Alex
- 75,813
- 86
- 255
- 348
-
The duplication of Int32 is interesting. What are you trying to do? – Austin Salonen Jun 08 '10 at 04:53
-
I have to associate two different numbers semantically with one string, which will then be used to render data in a view. – Alex Jun 08 '10 at 04:56
-
I think @Alex has `java` background such as me. – Davut Gürbüz Jul 16 '13 at 07:33
4 Answers
14
Best way is to create a container for it ie a class
public class Container
{
public int int1 { get; set; }
public int int2 { get; set; }
public string string1 { get; set; }
}
then in the code where you need it
List<Container> myContainer = new List<Container>();

Jason Jong
- 4,310
- 2
- 25
- 33
-
4+1 since it doesn't require a .Net4 tuple and can be trivially implemented with a class, but -1 because you should avoid public fields on a class. Implement as a property and use simple `{get; set;}` instead. – Robert Paulson Jun 08 '10 at 05:01
-
-
1type Container should be an immutable struct since it only represent values. – this. __curious_geek Jun 08 '10 at 05:10
-
1Depending on the implementation needs for Alex, he can decide if he needs an Equals to, and also decide Class Vs Struct, again depending on the needs of his project, however if its just for storing values, then a struct would make sense. – Jason Jong Jun 08 '10 at 05:21
1
Well, you can't do this til C# 3.0, use Tuples if you can use C# 4.0 as mentioned in other answers.
However In C# 3.0 - create an Immutable structure
and wrap all types' insances within the structure and pass the structure type as generic type argument to your list.
public struct Container
{
public string String1 { get; private set; }
public int Int1 { get; private set; }
public int Int2 { get; private set; }
public Container(string string1, int int1, int int2)
: this()
{
this.String1 = string1;
this.Int1 = int1;
this.Int2 = int2;
}
}
//Client code
IList<Container> myList = new List<Container>();
myList.Add(new Container("hello world", 10, 12));
If you're curious why create immutable structs - checkout here.

Community
- 1
- 1

this. __curious_geek
- 42,787
- 22
- 113
- 137
0
Based on your comment, it sounds like you need a struct with two integers stored in a dictionary with a string key.
struct MyStruct
{
int MyFirstInt;
int MySecondInt;
}
...
Dictionary<string, MyStruct> dictionary = ...

Austin Salonen
- 49,173
- 15
- 109
- 139