-1

I am trying to map datatable row to object. (C#)

I have Datatable like this.

|----|------|---------|
|ID  | Name | Address |
|----|------|---------|
| 1  | Tom  | USA     |
|----|------|---------|
| 2  | Tim  | AU      |
|----|------|---------|

And I have Object

Contact {
int ID,
String Name,
String Address
}

And I want to map dynamically like

Contact contact = new Contact();

foreach (var row in rows) {
   foreach(var col in table.Columns)
     contact[col.ColumnName] = row[col.ColumnaName]
}

Like Javascript, Is there any way to set value in object by columnName?

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
user3289230
  • 431
  • 2
  • 6
  • 19
  • 2
    Reflection, or automapper (maybe), or Dapper (maybe)? – ProgrammingLlama Feb 18 '19 at 08:56
  • 2
    Possible duplicate of [Can I set a property value with Reflection?](https://stackoverflow.com/questions/7718792/can-i-set-a-property-value-with-reflection) – Luc Feb 18 '19 at 08:56
  • So which row means 1st or 2nd row your want to map to Contact object? or you want all the rows to list of contact object – er-sho Feb 18 '19 at 08:56
  • @John, automapper is very slow, what is it for? Reflection, Emitmapper, mapster – pasha goroshko Feb 18 '19 at 09:00
  • [here](https://codereview.stackexchange.com/a/56857) is an example how to map DataTable to object. – Renatas M. Feb 18 '19 at 09:03
  • @pasha I was suggesting a number of ways to do it. Perhaps you didn't see the other suggestions? I'm not sure what _"what is it for"_ means? If you say it's slow, surely you already understand its function? – ProgrammingLlama Feb 18 '19 at 09:33

1 Answers1

0

Create a Contact class like this:

    public class Contact
    {
        private int ID;
        private string Name;
        private string Address;

        public Contact(int _ID, string _Name, string _Address)
        {
            ID = _ID;
            Name = _Name;
            Address = _Address;
        }
    }

After that you can create a contact like this: Contact c = new Contact(1, "Tom", "Berlin");

You can wrap your foreach arround it and use your DataRow to fill the Contact.

like so:

        DataTable dt = new DataTable(); // Fill this table            

        foreach (var row in dt.Rows)
        {
            Contact c = new Contact(row["ID"], row["Name"], row["Address"]);
        }
MaxW
  • 421
  • 1
  • 7
  • 22