C#使用循环向Dictionary添加值

时间:2017-04-27 19:50:55

标签: c# easypost

我使用EasyPost(运费API)来获取运费。

我能够对货件进行硬编码,但这对我没有帮助。我需要根据用户选择的内容添加数据。

以下是我的代码。如您所见,我有两个目前硬编码的货件。我想删除硬编码的货件并在其周围添加一个循环并以此方式添加货件。我可以通过变量传递包类型和权重。

因此,如果用户有5个包裹,我想添加5个货物。

提前致谢!

List<Dictionary<string, object>> shipments;

 shipments = new List<Dictionary<string, object>>() {
            new Dictionary<string, object>() {
                {"parcel", new Dictionary<string, object>() {{ "predefined_package", "MediumFlatRateBox" },  { "weight", 5 }}}
            },
            new Dictionary<string, object>() {
                {"parcel", new Dictionary<string, object>() {{ "predefined_package", "LargeFlatRateBox" },  { "weight", 15 }}}
            }
        };
parameters = new Dictionary<string, object>() {
            {"to_address", toAddress},
            {"from_address", fromAddress},
            {"reference", "USPS"},
            {"shipments", shipments}
                 };

Order order = Order.Create(parameters);

1 个答案:

答案 0 :(得分:2)

您可以遍历您的软件包列表,并将项目添加到字典列表中。

List<Package> packages = new List<Package>();
// add your packages here ...

List<Dictionary<string, object>> shipments = new List<Dictionary<string, object>>();
foreach(var p in packages){
    shipments.Add(new Dictionary<string, object>() {
          {"parcel", 
           new Dictionary<string, object>() {
               { "predefined_package", "MediumFlatRateBox" },  
               { "weight", p.Weight }}}
            });
}

这不是问题的关键,但如果您尝试通过POST JSON与HTTP通过HTTP进行通信(据我所知,您的目标是在https://www.easypost.com/docs/api.html#shipments调用API) ,使用匿名类型的对象会更具可读性,更具惯用性:

var shipments = new List<object>();
foreach(var p in packages){
    shipments.Add(new {
          parcel = new {
              predefined_package = "MediumFlatRateBox",
              weight = p.Weight
          }
    });
}

var parameters = new {
   to_address = toAddress,
   from_address = fromAddress,
   reference = USPS,
   shipments = shipments
};

(对于缩进感到抱歉,我没有触及IDE)

此外,文档还表明,EasyPost有一个C#库,用于您正在尝试的内容,它已经具有所有正确的类型,因此您不需要在整个地方使用词典。请参阅:https://github.com/EasyPost/easypost-csharp

Parcel parcel = new Parcel() {
    length = 8,
    width = 6,
    height = 5,
    weight = 10
};

Shipment shipment = new Shipment() {
    from_address = fromAddress,
    to_address = toAddress,
    parcel = parcel
};