简体   繁体   English

如果var为null,如何忽略c#

[英]How to ignore if var is null c#

I'm joining a load of strings to make a superstring but i need to ignore a param if one is null. 我加入了一个字符串加载来制作一个超级字符串,但如果一个为空,我需要忽略一个参数。 Currently i cannot think how to do this other than emcompassing all the params in seperate if statements. 目前我无法想到如何做到这一点,除了在单独的if语句中包含所有参数。 Help pls: 帮助请:

Here the code 这里的代码

 public void LinkBuilder(string baselink, string sharedkey, string service, string period, string bulletintype,
        string includeresults, string includemap, string username, string password)
    {
        sharedkey = "&" + sharedkey;
        service = "&" + service;
        period = "&" + period;
        bulletintype = "&" + bulletintype;
        includeresults = "&" + includeresults;
        includemap = "&" + includemap;
        username= "&" + username;
        password = "&" + password;

        string completeLink = sharedkey + service + period + bulletintype + includeresults + includemap + username +
                              password;

Not sure how to tackle this. 不知道如何解决这个问题。

I would really refactor it this way: 我真的会这样重构它:

public void LinkBuilder(params string[] links)
{
    string completeLink = String.Join("&", links.Where(x=>!String.IsNullOrEmpty(x)));
}

You can do a check of strings by operator ?: in method. 你可以通过运算符来检查字符串吗?:in method。

public void LinkBuilder(string baselink, string sharedkey, string service, string period, string bulletintype,
        string includeresults, string includemap, string username, string password)
    {
        sharedkey = checkValue(sharedkey);
        service = checkValue(service );
        period = checkValue(period );
        bulletintype = checkValue(bulletintype );
        includeresults = checkValue(includeresults );
        includemap = checkValue(includemap );
        username= checkValue(username );
        password = checkValue(password );

        string completeLink = sharedkey + service + period + bulletintype + includeresults + includemap + username +
                              password;
}
private String checkValue(String str)
{
    return str != null ? "&" + str : "";
}

Make an enumerable collection of your strings, use a bit of linq to filter out the nulls, then join it all back together again with String.Join : 创建一个可枚举的字符串集合,使用一些linq来过滤掉空值,然后使用String.Join将它们全部重新连接在一起:

var elements = 
    new[]{baselink, sharedkey, service, period, 
          bulletintype, includeresults, includemap, 
          username, password};
var nonNullElements = elements.Where(e => e != null);
var outputString = String.Join("&", nonNullElements);

On the off-chance that you're actually trying to assemble a querystring, there are better ways. 在您实际尝试组装查询字符串的可能性方面,有更好的方法。

For instance, you could leverage HttpUtility and reflection using the following method for parsing an anonymous object to a query string: 例如,您可以使用以下方法利用HttpUtility和reflection来将匿名对象解析为查询字符串:

public static class ObjEx
{
    public static string ToQueryString(this object data)
    {
        var collection = data.GetType()
            .GetProperties()
            .Aggregate(
                HttpUtility.ParseQueryString(string.Empty),
                (prev,curr) => {
                    var val = curr.GetValue(data);
                    var propName = curr.Name;
                    prev.Add(propName,val.ToString());
                    return prev;
            });
        return collection.ToString();
    }
}

then 然后

var data = new{foo = "bar", num = 1, cat = "bad", dog = "good", needsEscaping = "é\"&"};
Console.WriteLine(data.ToQueryString());

will give you: 会给你:

foo=bar&num=1&cat=bad&dog=good&needsEscaping=%u00e9%22%26

If the objective is to avoid wrapping each parameter in an if statement, you could add them to a list, then use String.Join , and Linq.Select 如果目标是避免在if语句中包装每个参数,可以将它们添加到列表中,然后使用String.JoinLinq.Select

        public void LinkBuilder(string baselink, string sharedkey, string service, string period, string bulletintype,
            string includeresults, string includemap, string username, string password)
    {
        var allParams = new List<string>
        {
            baselink,
            sharedkey,
            service,
            period,
            bulletintype,
            includeresults,
            includemap,
            username,
            password
        };

        var completeLink = "?" + String.Join("&", allParams.Select(p => p != null));
    }

Below would accept a Collection which I feel may be better maintainable. 下面会接受一个我觉得可以更好维护的Collection I re factored a bit. 我考虑了一下。

public string LinkBuilder(Dictionary<string, string> parameters)
{
     var url = String.Empty;
     foreach(var parameter in parameters)
         if(!string.IsNullOrEmpty(parameter.Value))
               url += String.Format("&{0}={1}", parameter.Key, parameter.Value);

     return url;
}

This way you would pass a collection to build your URL, then it would return the giant URL for you. 通过这种方式,您可以传递一个集合来构建您的URL,然后它会为您return巨大的URL。 You have a massive selection, I personally like Maksim's answer. 你有大量的选择,我个人喜欢马克西姆的回答。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM