Converting a Generic List to a CSV String

Converting a generic list to a CSV string

It's amazing what the Framework already does for us.

List<int> myValues;
string csv = String.Join(",", myValues.Select(x => x.ToString()).ToArray());

For the general case:

IEnumerable<T> myList;
string csv = String.Join(",", myList.Select(x => x.ToString()).ToArray());

As you can see, it's effectively no different. Beware that you might need to actually wrap x.ToString() in quotes (i.e., "\"" + x.ToString() + "\"") in case x.ToString() contains commas.

For an interesting read on a slight variant of this: see Comma Quibbling on Eric Lippert's blog.

Note: This was written before .NET 4.0 was officially released. Now we can just say

IEnumerable<T> sequence;
string csv = String.Join(",", sequence);

using the overload String.Join<T>(string, IEnumerable<T>). This method will automatically project each element x to x.ToString().

Generic List to CSV String

Your method can be simplified using StringBuilder and string.Join.

Concatenating strings directly is slow and uses a lot of memory which is fine for small operations.

See: Does StringBuilder use more memory than String concatenation?

private static string CreateCSVTextFile<T>(List<T> data, string seperator = ",")
{
var properties = typeof(T).GetProperties();
var result = new StringBuilder();

foreach (var row in data)
{
var values = properties.Select(p => p.GetValue(row, null));
var line = string.Join(seperator, values);
result.AppendLine(line);
}

return result.ToString();
}

A more complete implementation for CSVs:

private static string CreateCSVTextFile<T>(List<T> data)
{
var properties = typeof(T).GetProperties();
var result = new StringBuilder();

foreach (var row in data)
{
var values = properties.Select(p => p.GetValue(row, null))
.Select(v => StringToCSVCell(Convert.ToString(v)));
var line = string.Join(",", values);
result.AppendLine(line);
}

return result.ToString();
}

private static string StringToCSVCell(string str)
{
bool mustQuote = (str.Contains(",") || str.Contains("\"") || str.Contains("\r") || str.Contains("\n"));
if (mustQuote)
{
StringBuilder sb = new StringBuilder();
sb.Append("\"");
foreach (char nextChar in str)
{
sb.Append(nextChar);
if (nextChar == '"')
sb.Append("\"");
}
sb.Append("\"");
return sb.ToString();
}

return str;
}

Using: escaping tricky string to CSV format

Convert List to csv String

Here is something I have implemented that takes an object and reads the property values then formats it as a csv'd string.

The Write.WriteObject() is an example of how you would use it.

public static class StringExtensions
{
public static string ToCSV(this object field, bool first)
{
if(field != null)
{
string retVal = field.ToString();
retVal = retVal.Contains(",") || retVal.Contains("\"") || retVal.Contains("\r\n")
? "\"" + retVal + "\"" : retVal;
retVal = first ? retVal : "," + retVal;
return retVal;
}
else
{
return first ? "" : ",";
}
}
}

public class Format
{
public string CommaSeparatedObject(Type layoutType, object value, bool header)
{
bool first = true;

string retVal = "";
PropertyInfo[] props = layoutType.GetProperties();

if (header)
{
foreach (PropertyInfo prop in props)
{
retVal += prop.Name.ToCSV(first);
first = false;
}
}
else
{
foreach (PropertyInfo prop in props)
{
retVal += prop.GetValue(value).ToCSV(first);
first = false;
}
}

return retVal;
}
}

public class Write
{
public void WriteObject(IEnumerable<myClass> myObj)
{
StreamWriter sw = new StreamWriter(parameters.OutputFile, true, Encoding.ASCII, 16 * 1024);

sw.WriteLine(new Format().CommaSeparatedObject(typeof(myClass), item, true))); //write header

foreach(var item in myObj)
{
sw.WriteLine(new Format().CommaSeparatedObject(typeof(myClass), item, false)));
}
}
}

How to create a CSV string from a Generic ListT

string list = "";
foreach (ReportCriteriaItem item in GetCurrentSelection(...)) {
if (!string.IsNullOrEmpty(list)) list += ",";
list += item.???;
}
// do something with the list.

Convert a list into a comma-separated string

Enjoy!

Console.WriteLine(String.Join(",", new List<uint> { 1, 2, 3, 4, 5 }));

First Parameter: ","
Second Parameter: new List<uint> { 1, 2, 3, 4, 5 })

String.Join will take a list as a the second parameter and join all of the elements using the string passed as the first parameter into one single string.

Convert List of Data to csv file

The format of the csv file is as follows

Year,Make,Model,Length
1997,Ford,E350,2.35
2000,Mercury,Cougar,2.38

The following code shows how to implement it or you can use ready-made libraries.

public void WriteToCSV()
{
var csv = new StringBuilder();
foreach (var item in list1)
{
string line = "field1,field2,...";
csv.AppendLine(line);
line = string.Format("{0},{1},...",item.field1,...);
csv.AppendLine(line);
}
//.........................................
//.........................................
foreach (var item in list5)
{
string line = "field1,field2,...";
csv.AppendLine(line);
line = string.Format("{0},{1},...",item.field1,...);
csv.AppendLine(line);
}

string fileName = @"D:\WriteText.csv";
if (File.Exists(fileName))
System.IO.File.AppendAllText(fileName, csv.ToString());
else
System.IO.File.WriteAllText(fileName, csv.ToString());
}

Fastest way to convert a list of objects to csv with each object values in a new line

Use servicestack.text

Install-Package ServiceStack.Text

and then use the string extension methods ToCsv(T)/FromCsv()

Examples:
https://github.com/ServiceStack/ServiceStack.Text

Update:
Servicestack.Text is now free also in v4 which used to be commercial. No need to specify the version anymore! Happy serializing!

Java 8 : Comma separated string to Generic List using Stream.of()

The BigInteger::new step executes a Function<String, BigInteger> to convert each string to an instance of BigInteger. If you want to do this for a generic type, you need a function to convert a string to an instance of your generic type. That means you need a Function<String, T>.

Given Function<String, T> converter, you can do:

List<T> items = Stream.of(str.split(","))
.map(String::trim)
.map(converter)
.collect(Collectors.toList());


Related Topics



Leave a reply



Submit