在上游,它们可能为null时向字典添加值

时间:2014-04-15 16:19:59

标签: c# dictionary null

有没有办法清理它?当媒体,广告客户,产品等都是null时,我设法解决了这个问题。如果没有编写15+ if语句,有没有办法在有值时插入值,在没有值时忽略?例如,如果estimate!= null,但estimate["EndDate"] == null,我仍想捕获estimate["StartDate"] ...

// declare the buy type container
Dictionary<string, object> buyType = new Dictionary<string, object>();

// get the buy type objects
Dictionary<string, object> media = (Dictionary<string, object>)detail["Media"];
Dictionary<string, object> advertiser = (Dictionary<string, object>)detail["Advertiser"];
Dictionary<string, object> product = (Dictionary<string, object>)detail["Product"];
Dictionary<string, object> estimate = (Dictionary<string, object>)detail["Estimate"];

buyType.Add("CampaignId", campaignContainer["id"].ToString());
buyType.Add("PublicId", campaignContainer["PublicId"].ToString());
buyType.Add("BuyType", detail["BuyType"].ToString());
if (media != null)
{
    buyType.Add("MediaCode", media["Code"].ToString());
    buyType.Add("MediaName", media["Name"].ToString());
}
if (advertiser != null)
{
    buyType.Add("AdvertiserCode", advertiser["Code"].ToString());
    buyType.Add("AdvertiserName", advertiser["Name"].ToString());
    buyType.Add("AdvertiserBusinessKey", advertiser["BusinessKey"].ToString());
}
if (product != null)
{
    buyType.Add("ProductCode", product["Code"].ToString());
    buyType.Add("ProductName", product["Name"].ToString());
    buyType.Add("ProductBusinessKey", product["BusinessKey"].ToString());
}
if (estimate != null)
{
    buyType.Add("EstimateCode", estimate["Code"].ToString());
    buyType.Add("EstimateName", estimate["Name"].ToString());
    buyType.Add("EstimateBusinessKey", estimate["BusinessKey"].ToString());
    buyType.Add("EstimateStartDt", estimate["StartDate"].ToString());
    buyType.Add("EstimateEndDt", estimate["EndDate"].ToString());
}
buyType.Add("CreatedBy", System.Reflection.Assembly.GetExecutingAssembly().FullName.ToString());
buyType.Add("CreatedDt", DateTime.Now.ToString());

1 个答案:

答案 0 :(得分:2)

简短的回答是否定的,你无法绕过空检查。

你有几个选择:

  1. 将整个事物包裹在try catch中(甚至每个Add个调用)。这样可以防止事情爆炸,但是如果你把整个东西包起来,抛出线之后的任何一行都不会运行,如果你做了每一行,你也可以编写if语句。

  2. 使用null coalescing运算符将defalut值放在null的情况下:

    buyType.Add("EstimateEndDt", estimate["EndDate"] ?? String.Empty);
    

    你需要一个字符串强制转换或者什么,因为.ToString()之前的??检查仍然会抛出。

  3. 使用三元运算符代替if:

     buyType.Add("EstimateEndDt", estimate["EndDate"] == null ? String.Empty : estimate["EndDate"].ToString());
    
  4. 这与if语句相同,但稍短一点!