Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Tuple Using List of datatype of string in c#

Tags:

c#

list

tuples

I need to create Tuple from list of datatype in string, but did not get any solution.

Here is example of what I want to do.

string[] dataType = {"int", "float", "datetime"};

//I want to create list like this but dynamically datatype come from db.
//List<Tuple<int, string, string>> list = new List<Tuple<int, string, string>>(); 

List<Tuple<dataType[0],dataType[1], dataType[2]>> list = new List<Tuple<dataType[0],dataType[1], dataType[2]>>();
//Here datatype value is in string so I want to convert string to actual datatype.

Or if any alternative solution for this please guide me.

like image 562
Pravin Tukadiya Avatar asked Nov 16 '22 13:11

Pravin Tukadiya


1 Answers

This is to extend my comments under question, and show you what I meant there.

It is not hard to create a list of Tuple dynamically from list of types in string format. For example, use reflection:

private Type InferType(string typeName)
{
    switch (typeName.ToLowerInvariant())
    {
        case "int":
            return typeof(int);
        case "float":
            return typeof(float);
        default:
            return Type.GetType($"System.{typeName}", true, true);
    }
}

private object CreateListOfTupleFromTypes(string[] types)
{
    var elementTypes = types.Select(InferType).ToArray();

    // Get Tuple<,,>
    var tupleDef = typeof(Tuple)
        .GetMethods(BindingFlags.Static | BindingFlags.Public)
        .First(mi => mi.Name == "Create"
            && mi.GetParameters().Count() == elementTypes.Length)
        .ReturnType
        .GetGenericTypeDefinition();

    // Get Tuple<int, float, DateTime>
    var tupleType = tupleDef.MakeGenericType(elementTypes);

    // Get List<Tuple<int, float, DateTime>>
    var listType = typeof(List<>).MakeGenericType(tupleType);

    // Create list of tuple.
    var list = Activator.CreateInstance(listType);

    return list;
}

The problem is because the list is created using types only known at runtime, in your code, you can never use the list as strong typed list. i.e.List<Tuple<int, float, DateTime>>.

Of course, you could make life easier when the list is used in your code by using ITuple:

var list = new List<ITuple>();
list.Add(new Tuple<int, float, DateTime>(...);

int value1 = (int)list[0][0];
float value1 = (float)list[0][1];
DateTime value1 = (DateTime)list[0][2];

However, if you do that, then there is no point to use Tuple. You only need List<object[]>.

So, this comes back to my question, what is the list of tuple for in your code?

like image 176
weichch Avatar answered Dec 05 '22 03:12

weichch