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 });
As said by Scott Chamberlain(and several others), Tuples work best if you don't mind having immutable(ie read-only) objects.
If, like suggested by David, you want to reference the int by the string value, for example, you should use a dictionary
If, however, you want to store your elements mutably in a list, and don't want to use a dictionary-style referencing system, then your best bet(ie only real solution right now) would be to use KeyValuePair, which is essentially std::pair for C#:
Of course, this is stackable, so if you need a larger tuple(like if you needed 4 elements) you just stack it. Granted this gets ugly really fast:
So obviously if you were to do this, you should probably also define an auxiliary function.
My advice is that if your tuple contains more than 2 elements, define your own class. You could use a typedef-esque using statement like :
but that doesn't make your instantiations any easier. You'd probably spend a lot less time writing template parameters and more time on the non-boilerplate code if you go with a user-defined class when working with tuples of more than 2 elements
To add to what other suggested I like the following construct to avoid the annoyance of adding members to keyvaluepair collections.
What this means is that the constructor can be initialized with better syntax::
I personally like the above code over the more verbose examples Unfortunately C# does not really support tuple types natively so this little hack works wonders.
If you find yourself really needing more than 2, I suggest creating abstractions against the tuple type.(although
Tuple
is a class not a struct likeKeyValuePair
this is an interesting distinction).Curiously enough, the initializer list syntax is available on any
IEnumerable
and it allows you to use anyAdd
method, even those not actually enumerable by your object. It's pretty handy to allow things like adding anobject[]
member as aparams object[]
member.If appropriate, you might use a Dictionary which is also a generic collection:
If you are using .NET 4.0 you can use a
Tuple
.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).
Another solution create generic list of anonymous type.
This also gives you
intellisense
support, I think in some situations its better thanTuple
andDictionary
.For those wanting to use a Class.
Create a Class with all the parameters you want
Create a list with the class as parameter