Reputation: 15430
I am using below code :
var list = new Collection<ArrayList>
{
new ArrayList
{
1,
"Test1"
},
new ArrayList
{
2,
"Test2"
},
};
In the above code I want to avoid the ArrayList and use the Generics. Is it possible in the above code?
Edit: Above I have used only two values in one arraylist object, I may have multiple items of int's and string's in it.
Upvotes: 1
Views: 2303
Reputation: 25166
I'm not sure what you are actually trying to achieve, but it seems to me you are trying to mimic the behavior of a dictionary or map, that can map two different values to each other. These values could be of any type you want.
Something like this:
Dictionary<int, string> d = new Dictionary<int, string>();
d.Add(1, "Test1");
d.Add(2, "Test2");
and you can handle your data as simple as:
string t1 = d[1]; //will hold "Test1"
string t2 = d[2]; //will hold "Test2"
Do you want something like this?
Upvotes: 0
Reputation: 4966
Maybe you need Dictionary?
var list = new Dictionary<int, string>
{
{ 1, "Test1" },
{ 2, "Test2" }
};
Upvotes: 1
Reputation: 498972
You can't mix types in a generic list (unless the generic type is object
, but that equates to ArrayList
and is just a perversion of generics).
But you can create a class that contains a string
and int
and use that as the generic parameter for a generic list.
public class MyClass
{
public MyString string { get; set; }
public MyInt int { get; set; }
}
var list = new Collection<MyClass>
{
new MyClass { MyInt = 1, MyString = "Test1" },
new MyClass { MyInt = 2, MyString = "Test2" }
}
Another alternative, if using .NET 4.0 is to use a Tuple
, though I would rather have a strongly typed class.
(untested code):
var list = new Collection<Tuple<int,string>>
{
Tuple.Create(1, "Test1"),
Tuple.Create(2, "Test2")
}
Upvotes: 6
Reputation: 2499
var list = new List < Dictionary<int, string>> ();
then you can populate it was data as you need.
Upvotes: 0
Reputation: 14757
Not really, the fact that you have different types makes using a generic pointless.
You could use List<object>
instead of ArrayList but there's really no point. Instead you could create a custom class to hold the 2 values and use that in a generic type.
John
Upvotes: 2
Reputation: 887375
No.
The whole point of generics is that you can't put an int
and a string
in the same collection.
Instead, you should create your own class with int
and string
properties, then create a generic collection of that class.
Upvotes: 4