1

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

Saurabh R S
  • 3,037
  • 1
  • 34
  • 44

1 Answers1

2

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);
}
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
  • Brilliant! That makes perfect sense now that I see it  Works like a charm, though I did have to explicitly declare row as a DataRow otherwise I get an error on row[“ShippingAddresssCode”] of Cannot apply indexing with [] to an expression of type ‘object’ – Christian Kellermann Sep 20 '12 at 08:15
  • 1
    @user1683734: Yes, that is necessary, because DataTable.Rows is no strong typed collection. I fixed my answer. – Daniel Hilgarth Sep 20 '12 at 08:20