Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple parameters in a List. How to create without a class?

Tags:

c#

list

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 }); 
like image 669
Darcy Avatar asked Nov 23 '10 21:11

Darcy


2 Answers

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).

like image 120
Mark Byers Avatar answered Sep 20 '22 15:09

Mark Byers


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

like image 31
Scott Chamberlain Avatar answered Sep 22 '22 15:09

Scott Chamberlain