I have class person
that contain FirstName
and LastName
,
I'd like to create an array of person
which is populated from a DataTable
with columns Fname
and Lname
.
How would I do that?
I have class person
that contain FirstName
and LastName
,
I'd like to create an array of person
which is populated from a DataTable
with columns Fname
and Lname
.
How would I do that?
Here's a naive solution for you. Ideally, you would post something simple like this and ask for ways to improve/simplify it. Also, it'd be helpful to know which version of C# you're using.
class Person
{
public string FirstName, LastName; // should use properties instead
public Person(string firstName, string lastName)
{
FirstName = firstName;
LastName = lastName;
}
}
Person[] AddPersons(DataTable table)
{
// naive approach
Person[] Persons = (Person[])Array.CreateInstance(typeof(Person),
table.Rows.Count );
for (int i = 0; i < table.Rows.Count; i++)
{
Persons[i] = new Person(
(string)table.Rows[i]["Fname"],
(string)table.Rows[i]["Lname"]);
}
return Persons;
}
LINQ to DataSets should make this easy:
// Reference System.Data.DataSetExtensions.dll
public class Person {
public string FirstName { get; set; }
public string LastName { get; set; }
}
Person[] ConvertFromTable(DataTable input) {
var persons = from r in input.AsEnumerable()
select new Person {
FirstName = (string)r["FName"],
LastName = (string)r["LName"]
};
return persons.ToArray();
}