Home > other >  How to convert List of objects to Tuple of objects in c#
How to convert List of objects to Tuple of objects in c#

Time:12-18

I have a List<object> and I want to convert it to Tuple<object, ..., object>. How can I do it for any Count of List (which is guaranteed to be short enough)?

CodePudding user response:

Note, that unlike List<T>, tuple can have very limited numer of fields (7 1 in .Net 7)

https://learn.microsoft.com/en-us/dotnet/api/system.tuple-8?view=net-7.0

If the list is short enough, you can try to create tuple with a help of reflection (i.e. to call the required Tuple.Create method):

using System.Linq;
using System.Reflection;

...

// List<T>, not necessary List<Object>
List<int> data = new List<int>() { 4, 5, 7 };

...

var tuple = typeof(Tuple)
  .GetMethods(BindingFlags.Static | BindingFlags.Public)
  .First(method => method.Name == "Create" && 
                   method.GetParameters().Length == data.Count)
  .MakeGenericMethod(Enumerable
     .Repeat(data.GetType().GenericTypeArguments[0], data.Count)
     .ToArray())
  .Invoke(null, data.Select(item => (object) item).ToArray());

// Let's have a look:
Console.Write(tuple);

Output:

(4, 5, 7)

Note, that in such implementation, all fields of the tuple are of the same type (which is taken from list declaration). If you want to use actual item types change MakeGenericMethod call

   ...

   .MakeGenericMethod(data.Select(item => item?.GetType() ?? typeof(object))
      .ToArray())

   ...
  • Related