johnnie
johnnie

Reputation: 2057

how to create a custom list c#

I am trying to create a custom list that will hold two values.

For example I have an enum:

public enum Type
{
   name,
   number,
   surname
}

so want I want to do is have a list that will hold the enum above, Type, and a value to go with it.

For example:

List<Type type, object value>

Please assist as to how i can go about accomplishing this.

Upvotes: 0

Views: 4836

Answers (3)

oopbase
oopbase

Reputation: 11415

You could create a generic list including a generic KeyValuePair or a Tuple:

List<KeyValuePair<Type, object>> myList = new List<KeyValuePair<Type, object>>();

List<Tuple<Type, object>> myList = new List<Tuple<Type, object>>();

This might be a simple solution for your problem.

Upvotes: 2

margabit
margabit

Reputation: 2954

If Type is going to be unique in the collection you can use a Dictionary:

 Dictionary<Type,object>

If Type is not going to be unique you can use a Tuple:

 List<Tuple<Type,object>>

Or you can make your own class and have a List of type your class as @oded suggested:

 List<MyValues>

Upvotes: 0

Oded
Oded

Reputation: 499372

There are many ways to skin this cat.

A good option, if you only need to use this list inside a single method is to use a List<Tuple<Type,object>>. See Tuple on MSDN.

If you do need to share the list across methods/classes, I suggest a custom type to hold both values:

public class MyValues
{
  public Type TheType { get; set; }
  public object TheObject { get; set; }
}

And use that with List<MyValues>.

Note: Your use of object as a generic type is a code smell. It defeats the reasons for using generics.

Upvotes: 4

Related Questions