开发者

How to join together some strings with conditions?

I have the next code:

string result = string.Join(",", 
someCondition1 ? str1 : string.Empty,
someCondition2 ? str2 : string.Empty,
someCondition3 ? str3 : string.Empty,
//some other conditions like th开发者_如何转开发ose
......
);

If I have:

someCondition1 = true; str1 = "aaa";
someCondition2 = false; str2 = "bbb";
someCondition3 = true; str3 = "ccc";

Then result looks like "aaa,,ccc" but I need "aaa, ccc" (there is NO empty string). Which is the best way to do this?


How about something like:

// Or use a List<string> or whatever...
string[] strings = new string[] { someCondition1 ? str1 : null,
                                  someCondition2 ? str2 : null,
                                  someCondition3 ? str3 : null };

// In .NET 3.5 
string result = string.Join(",", strings.Where(x => x != null));

Do you really need to have six separate variables though? If you already had a collection of values and conditions (whether separately or together) it would be more elegant.


What about just typing some if statements?

StringBuilder result = new StringBuilder();

if(someCondition1)
 result.Append(str1);
if(someCondition2)
 result.Append(str2);
if(someCondition3)
 result.Append(str3);


If you plan on doing this a lot, you might want to construct your own class to do this for you in a nice way. I'm not suggesting this is the best way, but it's always fun to make these kinds of things:

public static class BooleanJoiner
{
    public static string Join(params Tuple<bool, string>[] data)
    {
        StringBuilder builder = new StringBuilder();
        int curr = 0;
        foreach (Tuple<bool, string> item in data)
        {
            if (item.Item1)
            {
                if (curr > 0)
                    builder.Append(',');
                builder.Append(item.Item2);
            }
            ++curr;
        }
        return builder.ToString();
    }   // eo Join
}

Usage:

        string result = BooleanJoiner.Join(new Tuple<bool, string>(true, "aaa"),
                                           new Tuple<bool, string>(false, "bbb"),
                                           new Tuple<bool, string>(true, "ccc"));


Even you can use like this also

string result = (someCondition1 ? str1 + "," : String.Empty + (someCondition2 ? str2
+ ",": String.Empty) + (someCondition3 ? str3 : String.Empty);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜