I am trying to fill a Customer Model with rows from a datatable but have not been able to get the syntax correct. The original code was taken from this tutorial Your First ASP.NET Web API (C#).
I have added a DataTable to a Controller but I have not been able to figure out how to get the rows from the table into my Customer Model. I thoought I could do it with a foreach but as I said I can’t get the syntax correct. This is what I have
Customer[] customers = new Customer[]
{
//new Customer {Id = "123", FirstName = "Buk", LastName = "Hix" }
// Replace hard coded customer information with foreach loop.
//commented out because it causes compile warnings
//foreach (DataRow row in GetAllData().Rows)
//{
// yield return new Customer
// {
// CustomerId = Convert.ToString(row["CustomerId"]),
// FirstName = Convert.ToString(row["FirstName"]),
// LastName = Convert.ToString(row["LastName"])
// };
//}
};
public IEnumerable<Customer> GetAllCustomers()
{
return customers;
}
What is the best way to accomplish what I am trying to do?
You’re close. When creating an iterator (a function that returns an IEnumerable/IEnumerator that uses
yield), you just put the code in the body toyieldthe values as necessary. No need to throw them into another collection. The compiler will generate an iterator for the code.It would be nicer to use LINQ here though if you’re open to it.