Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / programming / string

String concatenation using LINQ to create a CSV/PSV string

4.67/5 (2 votes)
28 Jun 2011CPOL 14K  
Or even better:public static string Join(this IList list, string joinString) { StringBuilder result = new StringBuilder(); int listCount = list.Count; int listCountMinusOne = listCount - 1; if (list != null && listCount > 0) { ...
Or even better:

C#
public static string Join<T>(this IList<T> list, string joinString)
    {
        StringBuilder result = new StringBuilder();

        int listCount = list.Count;
        int listCountMinusOne = listCount - 1;

        if (list != null && listCount > 0)
        {
            if (listCount > 1)
            {
                for (var i = 0; i < listCount; i++)
                {
                    if (i != listCountMinusOne)
                    {
                        result.Append(list[i]);
                        result.Append(joinString);
                    }
                    else
                        result.Append(list[i]);
                }
            }
            else
                result.Append(list[0]);
        }

        return result.ToString();
    }

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)