Join collection of objects into comma-separated string

前端 未结 11 1322
无人共我
无人共我 2020-12-07 19:22

In many places in our code we have collections of objects, from which we need to create a comma-separated list. The type of collection varies: it may be a DataTable from whi

11条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-07 19:43

    You could write a function that transforms a IEnumerable into a comma separated string

    public string Concat(IEnumerable stringList)
    {
        StringBuilder textBuilder = new StringBuilder();
        string separator = String.Empty;
        foreach(string item in stringList)
        {
            textBuilder.Append(separator);
            textBuilder.Append(item);
            separator = ", ";
        }
        return textBuilder.ToString();
    }
    

    You can then use Linq to query your collection/dataset/etc to provide the stringList.

提交回复
热议问题