仅当C#中的值不为空时才将值添加到字符串中

时间:2015-02-21 20:07:18

标签: c#

我尝试创建一个API调用,将地址的各个部分传递给地址验证服务。该地址必须作为单个查询参数传递。

使用以下代码

string input_address = HttpUtility.UrlEncode( string.Format( "{0} {1} {2} {3}",
            location.Street1, location.Street2, location.City, location.PostalCode ) );

如果地址的所有部分都存在,查询会成功,但是如果缺少多个部分,那么+符号会累积,最后会出现类似的查询。 /?api_key=####&query=++ID1+1QD&limit=1由于额外的' +'而失败迹象。

如果不使用一组if语句,如果它们不为null,是否只能将值传递给字符串?

完整代码如下:

string input_key = GetAttributeValue( "APIKey" );
string input_address = HttpUtility.UrlEncode( string.Format( "{0} {1} {2} {3}",
    location.Street1, location.Street2, location.City, location.PostalCode ) );

var client = new RestClient("https://api.ideal-postcodes.co.uk/");
var request = new RestRequest( Method.GET );
request.RequestFormat = DataFormat.Json;
request.Resource = "v1/addresses/";
request.AddParameter("api_key", input_key);
request.AddParameter("query", input_address);
request.AddParameter("limit", "1");
request.AddHeader("Accept", "application/json");
var response = client.Execute( request );

1 个答案:

答案 0 :(得分:5)

对于核心问题,是否可以仅在不使用一组if语句的情况下将值传递给字符串?

string[] addressParts = 
   { location.Street1, location.Street2, location.City, location.PostalCode};

string inputAddress = string.Join(" ", addressParts.Where(s=> !string.IsNullOrEmpty(s)));
inputAddress = HttpUtility.UrlEncode(inputAddress);