tags:

views:

113

answers:

2

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?

+1  A: 

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;
}
Michael Haren
Yeah, this would do as a quick and dirty solution. Ideally, I would think you would want to use a strongly-typed dataset to make things easier. Perhaps there would even be no need for custom classes then, and you could use the DataSet ones directly?
Noldorin
@Noldorin: yeah, I intentionally posted the most basic way I could think of since @Gold hadn't done any work yet. That's a good tip. If he's using C#3, there are a lot of neat ways to improve this and trim it down to a couple lines.
Michael Haren
+1  A: 

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();
}
Richard
Very nice--that'd be my solution if I knew he was using c#3
Michael Haren
Thank's a lot !!
Gold