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 .