Pick values from a dynamic list

3

I have a list of type dynamic :

private List<dynamic> listServicos = new List<dynamic>();

And it's being populated like this:

listServicos.Add(new { Codigo = txtCodServico.Text, Servico = txtNomeServico.Text, Quantidade = txtQuantidadeServico.Text, Preco = txtPrecoUniServico.Text });

I would like to get the values of lista , but I can not. I was trying this way:

foreach (var listServico in listServicos)
{                
    var codigo = listServico.Codigo;               
}

Visual Studio reports error:

    
asked by anonymous 28.12.2015 / 16:37

2 answers

3

I have not yet found a better solution, just one using ExpandoObject :

dynamic obj = new ExpandoObject();
obj.Codigo = "Código";
obj.Servico = "Serviço";
obj.Quantidade = "Quantidade";
obj.Preco = "Preço";
var listServicos = new List<dynamic>{ obj };
WriteLine(listServicos[0].Codigo);

See working on dotNetFiddle .

I wonder if you really need this. It may be that the solution is simpler than this. It's rare that anyone needs anything really dynamic.

This may be the solution:

var list = Enumerable.Empty<object>()
             .Select(r => new { Codigo = "Codigo", Servico = "Servico", Quantidade = "Quantidade", Preco = "Preco" })
             .ToList();
list.Add(new { Codigo = "Codigo", Servico = "Servico", Quantidade = "Quantidade", Preco = "Preco" });
WriteLine(list[0].Codigo);

See working on dotNetFiddle .

Another solution is to generalize rather than energize:

public static void Main() {
    var list = ToAnonymousList(new { Codigo = "Codigo", Servico = "Servico", Quantidade = "Quantidade", Preco = "Preco" });
    WriteLine(list[0].Codigo);
}
public static IList<T> ToAnonymousList<T>(params T[] items) {
    return items;
}

See working on dotNetFiddle .

I found these in SO .

No need for an auxiliary method:

var list = new[] { new { Codigo = "Codigo", Servico = "Servico", Quantidade = "Quantidade", Preco = "Preco" } }.ToList();
WriteLine(list[0].Codigo);

See working on dotNetFiddle .

    
28.12.2015 / 17:35
0

1 - Adds the reference to Microsoft.Csharp .

If you already have the reference, remove it and insert it again.

Look at this answer , I believe I can help you.

2 - Another possible solution is to change the framework from 4.5 to 4.5.1. ( Font ) Just go to Web.config and change:

<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />

To:

<compilation debug="true" targetFramework="4.5.1" />
<httpRuntime targetFramework="4.5.1" />

rebuild.

3 - Another attempt is to change Copy Local = True to reference Microsoft.CSharp

    
28.12.2015 / 16:45