Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

185
Visualizações
how to iterate over tuple items

How to iterate over items in a Tuple, when I dont know at compile-time what are the types the tuple is composed of? I just need an IEnumerable of objects (for serialization).

private static IEnumerable TupleToEnumerable(object tuple)
{
    Type t = tuple.GetType();
    if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Tuple<,>))
    {
        var x = tuple as Tuple<object, object>;
        yield return x.Item1;
        yield return x.Item2;
    }
}
about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

You can access properties and their values by reflection with Type.GetProperties

var values = tuple.GetType().GetProperties().Select(p => p.GetValue(tuple));

So your method will be very simple Linq query

private static IEnumerable TupleToEnumerable(object tuple)
{
    // You can check if type of tuple is actually Tuple
    return tuple.GetType()
        .GetProperties()
        .Select(property => property.GetValue(tuple));
}
about 4 years ago · Santiago Trujillo Relatório

0

In .NET Core 2.0+ or .NET Framework 4.7.1+, there are

  • t.Length
  • t[i]

it's from an interface ITuple interface

var data = (123, "abc", 0.983, DateTime.Now);
ITuple iT = data as ITuple;

for(int i=0; i<iT.Length;i++)
  Console.WriteLine(iT[i]);
about 4 years ago · Santiago Trujillo Relatório

0

An issue here is that you have to deal with multiple Tuple types: Tuple<T1, T2>, Tuple<T1, T2, T3> etc. (I'm assuming that you want this to work with tuples with an arbitrary number of items.)

A somewhat hacky way of doing this it to see if the name of the type begins with System.Tuple:

public static IEnumerable TupleToEnumerable(object tuple)
{
    Type t = tuple.GetType();

    if (t.IsGenericType && t.GetGenericTypeDefinition().FullName.StartsWith("System.Tuple"))
    {
        for (int i = 1;; ++i)
        {
            var prop = t.GetProperty("Item" + i);

            if (prop == null)
                yield break;

            yield return prop.GetValue(tuple);
        }
    }
}

If you don't like the hackyness of FullName.StartsWith(...) you can make it more typesafe like so:

public static IEnumerable TupleToEnumerable(object tuple)
{
    Type t = tuple.GetType();

    if (isTupleType(t))
    {
        for (int i = 1;; ++i)
        {
            var prop = t.GetProperty("Item" + i);

            if (prop == null)
                yield break;

            yield return prop.GetValue(tuple);
        }
    }
}

private static bool isTupleType(Type type)
{
    if (!type.IsGenericType)
        return false;

    var def = type.GetGenericTypeDefinition();

    for (int i = 2;; ++i)
    {
        var tupleType = Type.GetType("System.Tuple`" + i);

        if (tupleType == null)
            return false;

        if (def == tupleType)
            return true;
    }
}
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda