开发者

C# Switch results to list then to comma separated values

开发者 https://www.devze.com 2023-03-01 01:56 出处:网络
How would I make a switch state开发者_StackOverflow中文版ment populate a list, or comma delimited string?

How would I make a switch state开发者_StackOverflow中文版ment populate a list, or comma delimited string?

For example

switch(test)
{
   case 0:
      "test"
      break;
   case 1:
      "test2"
      break;
   case 2:
      "test3"
      break;
}

So my program will go into this statement multiple times. So lets say it goes in there twice and has case 2 and case 1. I woulld like a string value containing the following: string value = "test3, test2"


Looks like a List<string> would be ideal to hold your values, you can create a comma separated string from that using string.Join():

List<string> myList = new List<string>();
//add items
myList.Add("test2");

//create string from current entries in the list
string myString = string.Join("," myList);


By multiple times, you mean a loop? You can just have a string and concatenate the string using + operator, or you can just have a list and add to it everytime the case condition is satisfied.

But if you mean by conditional flow so that you want case 0, 1 and 2 to all be evaluated, then you can simply omit the break and do the same concatenation like I mentioned above.


 private string strValue = string.Empty;
 private string StrValue
 {
     get
     {
          return strValue ;
     }
     set
     {
          StrValue= string.Concat(strValue , ",", value);
     }
 }

switch(test)
{
case 0:
StrValue = "test"
break;

case1:
StrValue = "test2"
break;

case 2:
StrValue = "test3"
breakl
}

Where ever you used StrValue remove "," if "," comes in the last.


There's a couple ways you can do it, a very simple one is:

string csv = "";

while (yourCriteria) {
  string value;

  // insert code to get your test value

  switch(test)
  {
    case 0:
      value = "test";
      break;
    case1:
      value = "test2";
      break;
    case 2:
      value = "test3";
      break;
  }

  csv += value + ", ";
}

csv = csv.Length > 0 ? csv.Substring(0, csv.Length-2) : "";


Use a loop and a StringBuilder. If you're doing repeated concatenation, StringBuilders are significantly more efficient than naive string concatenation with +.

StringBuilder sb = new StringBuilder();

for(...)
{
    switch(test)
    {
        case 0:
        sb.Append("test");
        break;

        case1:
        sb.Append("test2");
        break;

        case 2:
        sb.Append("test3");
        break;
    }
}
0

精彩评论

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