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.

C# : To return a comma delimited list fr…

by Chris F Carroll read it in <1 min
0