TechyMedia

A .NET Technology blog | .NET,C# Progamming,C# tutorials,WPF WCF|Software Engineer

NAVIGATION - SEARCH

Initialize List<string> with strings In C# - Collection Initializer ,List<string> to CSV

C# initialize list - There are multiple ways to Initialize List&lt;string&gt; with strings In C# - Collection Initializer the new way.Also explaining C# How to create comma separated string from a List&lt;string&gt;,c# initialise list,c# initialise list of objects

There are multiple ways to Initialize C# List.Collection intializing was boring in old versions of .NET. For instance, to create a List<string> and populate it with string values are

List<string> stringList = new List<string>();
stringList.Add("This");
stringList.Add("Is");
stringList.Add("String");
stringList.Add("List");

Quite boring indeed.

With the introduction of Collection Initializers Initialize C# List is now very simple as below.

List<string> stringList= new List<string> {"This","Is","String","List"};

 

C# How to create comma separated string from a List<string>

The code sample below will help you to create a comma separated string from a string list, List<string> object.
   

List<string> stringList= new List<string>{"string","seperation","by","comma"}; 

    string csvString = string.Join(",", stringList);

 So csvString will be string,seperation,by,comma.

 

C# How to create char separated string from a List<string>

The method below will help to seperate the List<string> with any character passed as param.

public static string StringListSeperationByChar(List<string> stringList, string character)
{
return string.Join(character, stringList);
}

So do the method call as below to get ; seprated string,

string charSeperatedString = StringListSeperationByChar(stringList, ";");

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading