Lucas_Santos
Lucas_Santos

Reputation: 4740

Foreach in a IList with Anonymous Type

I have an IList and with QuickWatch I could see the following

Name                    Value                                 Type
ListStatusProposta      { Value = "1", Text = "Beginner" }    <Anonymous Type>
      Text              "Beginner"                            object{string}
      Value             "1"                                   object{string}

How can I do a foreach to access these properties ?

Update

This is how I fill my IList

protected static object[,] StatusProposta()
{
    object[,] status = {
    { "1", "Beginner" },
    { "2", "Intermediate" },
    { "3", "Advanced" }
                      };

    return status;
}


//public static IList fillLista(string nome)
public static IList<object> fillLista(string nome)
        {
            //List<dynamic> list = new List<dynamic>();
            List<object> list = new List<object>();
            object[,] objeto;

            switch (nome) 
            {                
                case "StatusProposta":
                    objeto = StatusProposta();
                    break;
                default:
                    objeto = null;
                    break;
            }            

            if (objeto != null)
            {
                for (int i = 0; i < (objeto.Length / 2); i++)
                    list.Add(new { Value = objeto[i, 0], Text = objeto[i, 1] });
            }

            return list;
        }



//IList ListaStatusProposta = fillLista("StatusProposta");
IList<object> ListaStatusProposta = fillLista("StatusProposta");
foreach()
{
// ????
}

Upvotes: 2

Views: 1750

Answers (1)

Oded
Oded

Reputation: 498992

The anonymous type does have properties that can be accessed as normal:

foreach(var item in myList)
{
   var val = item.Value;
   var txt = item.Text;
}

One of the issues here is that the return type of fillLista is IList and not a generic IList this causes all values in the list to be cast to object.

Return IList<dynamic> instead.

Upvotes: 7

Related Questions