Suppose I have this code (pseudocode)
class SomeClass
{
class Person
{
public static string Name { get; set; }
public static int Age { get; set; }
}
List<Person> person = new List<person>;
public void SelectPerson()
{
DataTable dt = new DataTable();
SqlConnection conn = GetConnection();
conn.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT name, age FROM person", conn);
da.Fill(dt);
}
}
Can I fill the List (person) based on the result of my DataAdapter? How should I do it? Or is there any workaround? Thanks...
The Fill method of the DataAdapter is used to populate a DataSet with the results of the SelectCommand of the DataAdapter . Fill takes as its arguments a DataSet to be populated, and a DataTable object, or the name of the DataTable to be filled with the rows returned from the SelectCommand .
Answers. Datareaders are fast compare to DataAdapters/DataSets because of the following reason. DataReader offers better performance because it avoids the performance and memory overhead associated with the creation of the DataSet.
Probably the best way is not to read into a datatable first:
var dr = new DataReader(....) // Fill in what is needed, can't remember offhand
while(dr.Next())
{
persons.Add(
new Person() {
Name = (string) r["Name"],
Age = (int) r["Age"]
}
);
}
Caveat: You want to close the DataReader/connection quickly, don't do lots of processing. The above code is more efficient than using a DataTable as an intermediary.
But if you do want to use a data table first, you could use LINQ:
var list = dt.AsEnumerable().Select(r => new Person() {
Name = (string) r["Name"],
Age = (int) r["Age"] }
).ToList()
or just itterate of dt.Rows and create a new person and add it to the list
You should also use Using() statements around your connection and reader.
There's also Linq to DataSet that you could use to do something along these lines
var list = (from tr in dt.AsEnumerable()
select new Person() {
Name = tr.Field<string>("Name"),
Age = tr.Field<int>("Age")
}).ToList();
Robert beat me to the answer, just using slightly different syntax.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With