Comma “izing” a list of items

前端 未结 10 1692
我寻月下人不归
我寻月下人不归 2021-02-04 08:53

Given a list of strings, what is the best method for concatenating these strings into a comma separated list with no comma at the end. (VB.NET or C#) (Using either StringBuilder

10条回答
  •  执念已碎
    2021-02-04 09:49

    There are several ways to do this, but they're basically variations on a theme.

    Pseudocode:

    For Each Item In Collection:
      Add Item To String
      If Not Last Item, Add Comma
    

    A different way that I like a little better is something like this:

    For Each Item In Collection:
      If Not First Item, Add Comma
      Add Item To String
    

    Edit: The reason I like the second way of doing it is that each item stands on its own. Using the first approach, if you modified your logic later so that a subsequent item might not get added, you could end up with a stray comma at the end of the string unless you also made your test in the previous item more intelligent, which is dumb.

提交回复
热议问题