
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Create Comma Separated String from a List of String in C#
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
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
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
Advertisements