Alon Ehrenlieb
Alon Ehrenlieb

Reputation: 9

Convert tuple to list

I need to convert different tuples to lists of strings.

How can i convert a tuple that contains different types to a list of strings in C#?

And of curse i need a generic solution for different tuples.

Example:

I want to convert this tuple to a list: ("word", 1, 's', US)

Upvotes: 0

Views: 5349

Answers (4)

Manish
Manish

Reputation: 6286

Try this:

using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            string x = null;

            var t = ("word", 1, 's', "US");
            foreach (var item in TupleToList(t))
            {
                Console.WriteLine(item);
            }
        }

        private static List<string> TupleToList(ITuple tuple)
        {
            var result = new List<string>(tuple.Length);
            for (int i = 0; i < tuple.Length; i++)
            {
                result.Add(tuple[i].ToString());
            }
            return result;
        }
    }
}

The TupleToList takes a ITuple as parameter and returns list of string. Goes without saying, there could be issues based on what the tuple contains which you might need to handle.

Upvotes: 0

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186833

Linq solution:

 using System.Linq;
 using System.Runtime.CompilerServices;

 ...

 public static List<string> TupleToList(ITuple value) {
   if (null == value)
     throw new ArgumentNullException(nameof(value));

   return Enumerable
     .Range(0, value.Length)
     .Select(i => value[i]?.ToString()) // ?. - don't call ToString() on null
     .ToList();
 }

Fiddle

Upvotes: 3

sabuj
sabuj

Reputation: 1

Use Value Tuple

var result = return (type1, type2, type3);

return new ModelDto()
            {
                Model1= result.Item1,
                Model2= result.Item2,
                Model3= result.Item3
            };

Upvotes: 0

Jacob Huckins
Jacob Huckins

Reputation: 378

Modified from Kobi Hari's answer from C# ValueTuple of any size

I added some LINQ to convert each element to a string before returning to fit the question requirements.

public List<string> TupleToStringList(ITuple tuple)
{
  var result = new List<object>(tuple.Length);
  for (int i = 0; i < tuple.Length; i++)
  {
    result.Add(tuple[i]);
  }
  return result.Select(obj => obj.ToString()).ToList();
}

Or using the original method and converting to strings as a separate step

public List<object> TupleToString(ITuple tuple)
{
  var result = new List<object>(tuple.Length);
  for (int i = 0; i < tuple.Length; i++)
  {
    result.Add(tuple[i]);
  }
  return result;
}

// your code
{
    ...
    List<object> objectList = TupleToString(tupleToConvert);
    List<string> stringList = objectList.Select(obj => obj.ToString());
}

Upvotes: 0

Related Questions