I still haven’t found a more suitable 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);
Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.
I wonder if you really need this. It may be that the solution is simpler than this. It is rare that someone needs something really dynamic.
This could 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);
Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.
Another solution is to generalize rather than streamline:
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) => items;
Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.
I found these in the OS.
Without needing an auxiliary method:
var list = new[] { new { Codigo = "Codigo", Servico = "Servico", Quantidade = "Quantidade", Preco = "Preco" } }.ToList();
WriteLine(list[0].Codigo);
Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.
What mistake is he accusing?
– Ricardo
@Ricardo Pergunta editada!
– Leonardo
Leonardo, can you tell us more about the project? I did a project here with a copy code of yours and it worked with all the frameworks I used, did you migrate from MVC 2 to 3 for example? Anything that’s been done to it could be the cause, because the code works...
– Ricardo
@Ricardo now I was curious to know how his worked. All the tests I did didn’t work. See wrong: https://dotnetfiddle.net/7EyQ0n
– Maniero
Strange, in fiddle does not work, if you create a new console project on your machine and put exactly your code it works... I still believe the problem is something of the environment.
– Ricardo
@Leonardo you really need the list to have dynamic elements, that is, they need to change their structure at runtime, or it was actually the solution you adopted to have an anonymous type, but it doesn’t need to be dynamic?
– Maniero
@bigown was actually a solution I adopted. It doesn’t have to be totally dynamic
– Leonardo
@Leonardo I’m thinking I’ve already given you a better answer.
dynamic
should be used as a last resort. You have to make sure that the solution can only be given in Runtime.– Maniero