'How to get the last item in foreach loop writing to CSV?
I'm having trouble getting the last item in the loop Writing to CSV, I don't want the last item in CSV to have a , at the end.
This is the public string to write my controller to CSV
public string WriteTsv<T>(IEnumerable<T> data)
{
StringBuilder output = new StringBuilder();
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
foreach (PropertyDescriptor prop in props)
{
output.Append(prop.DisplayName); // header
output.Append(", \t");
}
output.AppendLine();
foreach (T item in data)
{
foreach (PropertyDescriptor prop in props)
{
output.Append(prop.Converter.ConvertToString(
prop.GetValue(item)));
output.Append(", \t");
}
output.AppendLine();
}
return output.ToString();
}
I've been stuck on this for a while now hoping anyone could help.
Solution 1:[1]
You can use String.Join to combine an IEnumerable<T> with a separator and then use AppendLine to add to the output. I used Cast<T>() to convert the IEnumerable implementation from the legacy PropertyDescriptorCollection to a modern IEnumerable<T>. (Unfortunately, a lot of C# hasn't been updated to properly support IEnumerable<T>.)
public string WriteTsv<T>(IEnumerable<T> data) {
var output = new StringBuilder();
var props = TypeDescriptor.GetProperties(typeof(T)).Cast<PropertyDescriptor>();
// header
output.AppendLine(String.Join(",", props.Select(prop => prop.DisplayName)));
// data
foreach (T item in data)
output.AppendLine(String.Join(",", props.Select(prop => prop.Converter.ConvertToString(prop.GetValue(item)))));
return output.ToString();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | NetMage |
