I have the next object/list "ListaDatos" and I like to get it as clear string (to visualize/send this via mail, etc)
public List<Datos> ListaDatos = new List<Datos>();
public class Datos
{
public string Numero;
public string Alias;
public string URLConsumo;
//-- Consumos -----------------------------
public List<Consumo> Consumos = new List<Consumo>();
public string ConsumoTotal;
}
public class Consumo
{
public string Tipo;
public string Subtipo;
public string Concepto;
public string Cantidad;
public string Importe;
public string Total;
}
What is the easiest way to "render" this object into text to obtain a string variable with something like this:
DATOS
Numero : 10
Alias : "aaaaa"
urlConsumo : "www.aaaaaaaaaaaaa"
Consumos
Tipo : "abc"
SubTtipo : "aaa"
...
DATOS
Numero : 10
Alias : "aaaaa"
urlConsumo : "www.aaaaaaaaaaaaa"
Consumos
Tipo : "abc"
SubTtipo : "aaa"
...
Implement a
ToString()
method for theConsumo
class and then implement aToString()
method for theDatos
class using theToString()
method for theConsumo
class.You must override a "ToString" dafault function like:
refer to the escape sequences section in C# development guide... http://msdn.microsoft.com/en-us/library/h21280bw.aspx or http://msdn.microsoft.com/en-us/netframework/aa569608
When string representations are used for visualization and similar purposes, the best approach is to override
ToString
method. Start with the most nested type, and go up the hierarchy. UseToString
of nested objects to implementToString
of outer objects. One very useful method in formatting collections of objects isstring.Join()
: it lets you format a collection without an explicit loop.