开发者

C# inline conditional in string[] array

开发者 https://www.devze.com 2023-04-13 05:09 出处:网络
How could you do the following inline conditional for a string[] array in C#. Based on a para开发者_StackOverflow中文版meter, I\'d like to include a set of strings...or not. This question is a followu

How could you do the following inline conditional for a string[] array in C#. Based on a para开发者_StackOverflow中文版meter, I'd like to include a set of strings...or not. This question is a followup of this one on stackoverflow.

        //Does not compile
        bool msettingvalue=false;
        string[] settings;
        if(msettingvalue)
            settings = new string[]{
                "setting1","1",
                "setting2","apple",
                ((msettingvalue==true) ? "msetting","true" :)};

If msettingvalue is true, I'd like to include two strings "msetting","true" : otherwise no strings.

Edit1 It doesn't have to be a key value pair...what if it were 5 strings to be (or not to be) added...I didn't think it'd be that tricky.

(Also...could someone with enough rep make a "inline-conditional" or "conditional-inline" tag?)


settings = new string[]{"setting1","1", "setting2","apple"}
    .Concat(msettingvalue ? new string[] {"msetting","true"} : new string[0]);
    .ToArray()


use a generic List<String>

bool msettingvalue=false;
string[] settings;
var s = new List<String>();
s.AddRange({"setting1","1","setting2","apple"});
if(msettingvalue)
    s.AddRange({"msetting","true"});
settings = s.ToArray();

But... from the look of your array you'd be better off using a different structure to store these things. It's an associative array you want. You could use a Tuple or a Dictionary to model the settings in a way that is easier to handle, and that more accurately reflects the semantics.

bool msettingvalue=false;
var settings = new Dictionary<String,String>();
settings.Add("setting1","1");
settings.Add("setting2","value2");
if(msettingvalue)
    settings.Add({"msetting","true");

...the last two lines could even be.

settings.Add({"msetting",msettingvalue.ToString());
0

精彩评论

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

关注公众号