Multiple parameters in a List. How to create without a class?
This is probably a pretty obvious question, but how would I go about creating a List
that has multiple parameters without creating a class.
Example:
var list = new List<string, int>();
list.Add("hello", 1);
I normally would use a class like so:
public class MyClass
{
public String myString {get; set;}
public Int32 myInt32 {get; set;}
}
then create my list by doing:
var list = new List<MyClass>();
list.Add(new MyClass { myString = "hello", myInt32 = 1 });
If you are using .NET 4.0 you can use a Tuple
.
List<Tuple<T1, T2>> list;
For older versions of .NET you have to create a custom class (unless you are lucky enough to be able to find a class that fits your needs in the base class library).
If you do not mind the items being imutable you can use the Tuple class added to .net 4
var list = new List<Tuple<string,int>>();
list.Add(new Tuple<string,int>("hello", 1));
list[0].Item1 //Hello
list[0].Item2 //1
However if you are adding two items every time and one of them is unique id you can use a Dictionary
If appropriate, you might use a Dictionary which is also a generic collection:
Dictionary<string, int> d = new Dictionary<string, int>();
d.Add("string", 1);