C# : To return a comma delimited list from an array or collection of strings

Don’t:

            var description = new StringBuilder("");
            foreach (var item in productItems.Where(x => x.ItemType == type))
            {
                description.Append(item.Description + ", ");
            }
            return description.Remove(description.Length - 2, 2).ToString();

Do:

return string.Join(", ", productItems.Where(x => x.ItemType == type).Select(x => x.Description).ToArray());

because the first example fails when your collection has no elements.

Leave a Reply

Your email address will not be published. Required fields are marked *