How to create a comma separated string from a list of string in C#?

CsharpServer Side ProgrammingProgramming

A List of string can be converted to a comma separated string using built in string.Join extension method.

string.Join("," , list);

This type of conversion is really useful when we collect a list of data (Ex: checkbox selected data) from the user and convert the same to a comma separated string and query the database to process further.

Example

 Live Demo

using System;
using System.Collections.Generic;
namespace DemoApplication {
   public class Program {
      static void Main(string[] args) {
         List<string> fruitsList = new List<string> {
            "banana",
            "apple",
            "mango"
         };
         string fruits = string.Join(",", fruitsList);
         Console.WriteLine(fruits);
         Console.ReadLine();
      }
   }
}

Output

The output of the above code is

banana,apple,mango

Similarly, a property in a list of complex objects can also be converted to a comma separated string like below.

Example

 Live Demo

using System;
using System.Collections.Generic;
using System.Linq;
namespace DemoApplication {
   public class Program {
      static void Main(string[] args) {
         var studentsList = new List<Student> {
            new Student {
               Id = 1,
               Name = "John"
            },
            new Student {
               Id = 2,
               Name = "Jack"
            }
         };
         string students = string.Join(",", studentsList.Select(student => student.Name));
         Console.WriteLine(students);
         Console.ReadLine();
      }
   }
   public class Student {
      public int Id { get; set; }
      public string Name { get; set; }
   }
}

Output

The output of the above code is

John,Jack
raja
Published on 08-Aug-2020 14:25:51
Advertisements