mercoledì 27 luglio 2011

How To: DataTable To List

Questo post prosegue qui :how to datatable to list solved

Oggi ho notato che qualcuno ha fatto una ricerca sul mio sito in tal senso...

La cosa mi ha incuriosito e ho fatto una prova che però non mi ha del tutto soddisfatto, anzi cercherò più tardi di approfondire meglio la situazione.

public class entity
{
public int ID { get; set; }
public string Name{ get; set; }
public string Description { get; set; }

public entity(int id, string name, string description)
{
ID = id; Name = name; Description = description;
}
}

public class entityList:List<entity>
{
}

class Program
{
static void Main(string[] args)
{
DataTable dt = new DataTable("myEntity");
dt.Columns.Add("id", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Description", typeof(string));

dt.Rows.Add(new object[] { 1, "Test_1", "Test_1"});
dt.Rows.Add(new object[] { 2, "Test_2", "Test_2" });
dt.Rows.Add(new object[] { 3, "Test_3", "Test_3" });



entityList el = new entityList();
for (int i = 0; i < dt.Rows.Count; i++)
{
Console.WriteLine(
"Id:{0} Name:{1} Description:{2}",
dt.Rows[i][0].ToString(),
dt.Rows[i][1].ToString(),
dt.Rows[i][2].ToString()
);

el.Add(new entity(
(int)dt.Rows[i][0],
dt.Rows[i][1].ToString(),
dt.Rows[i][2].ToString()
)
);
}




for (int i = 0; i < el.Count; i++)
{
Console.WriteLine(
"Id:{0} Name:{1} Description:{2}",
el[i].ID.ToString(),
el[i].Name.ToString(),
el[i].Description.ToString()
);

}

Console.ReadLine();
}

}


Questo codice non mi convince del tutto perchè comunque devo passare tutti gli elmenti della tabella, e non credo che sia il migliore de modi... ma come
ho anticipato, troverò un sistema ... più migliore assai.

Nessun commento: