Question

I'm having some difficulty in iterating through a datatable and assigning each value to a given property in a datacontract list.

So I have the following DataContract:

namespace Shared.DataContracts
{
    [Serializable]
    [DataContract(Name = "DispatchAddress")]
    public class DispatchDetails
    {
        [DataMember(Name = "ShippingAddressCode")]
        public string ShippingAddressCode { get; set; }

        [DataMember(Name = "ShippingName")]
        public string ShippingName { get; set; }

        [DataMember(Name = "Address")]
        public Address Address { get; set; }

        [DataMember(Name = "ContactName")]
        public string ContactName { get; set; }

        //etc
    }
}

In my service I'd like to return a list of DispatchDetails, but my problem is in assigning values to each of the properties.

public GetDispatchDetailsResponse GetDispatchDetails(string code, string id)
{
    GetDispatchDetailsResponse getDispatchDetailsResponse = new GetDispatchDetailsResponse();

    List<DispatchDetails> dispatchDetails = new List<DispatchDetails>();

    DataTable dt = _dataRetriever.GetDataTable(string.Format(BusinessSqlConstants. DispatchAddress, code, id));

    foreach (var row in dt.Rows)
    {
        foreach (var col in dt.Columns)
        {
            //The troublesome line of code.
            dispatchDetails.Add("ShippingAddressCode") = Convert.ToString(dt.Columns["ShippingAddressCode"]);
            //etc
        }
    }
}

I've added my latest dodgy code line in to demostrate what I'm trying to accomplish. I've tried a few ways but seems I'm struggling to see the wood through the trees at the moment :)

Thanks in advance for any advice given.

Kind regards, Christian

Was it helpful?

Solution

Are you trying to do this?

foreach (DataRow row in dt.Rows)
{
    var item = new DispatchDetails();

    item.ShippingAddressCode = Convert.ToString(row["ShippingAddressCode"]);
    item.ShippingName = Convert.ToString(row["ShippingName"]);
    // etc.

    dispatchDetails.Add(item);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top