KG Sosa
KG Sosa

Reputation: 70

How to format a string inside an array?

I have this code

StringBuilder sb = new StringBuilder();
var columnNames = dt.Columns
    .Cast<DataColumn>()
    .Select(column => "\"" + column.ColumnName.Replace("\"", "\"\"") + "\"")
    .ToArray();
sb.AppendLine(string.Join(",", columnNames));
foreach (DataRow row in dt.Rows)
{
   var fields =   row.ItemArray
        .Select(field => "\"" + field.ToString().Replace("\"", "\"\"") + "\"")
        .ToArray();
   sb.AppendLine(string.Join(",", fields));
}

in row[1] and row[2] these are dates, I want them to be in this format

string.Format("{0:yyyy-MM-dd HH:mm:ss.fffffff}", row[1]);

How should i do that?

Upvotes: 0

Views: 450

Answers (3)

dav_i
dav_i

Reputation: 28107

Within your foreach loop, you could do something like this:

var dateFormat = "{0:yyyy-MM-dd HH:mm:ss.fffffff}";

var dateColumns = new[] { 1, 2 };

var fields = itemArray.Select((e, i) =>
{
    if (dateColumns.Contains(i))
        return String.Format(dateFormat, e);

    return e.ToString();
});

Upvotes: 0

Markus
Markus

Reputation: 22456

There is an overload of Select that takes a function of the value and the index as a parameter; you can use this to apply a different formatting based on the index. The following sample shows a function that formats the value. This function is used in the Select in your code:

private string FormatStringByIndex(object field, int index)
{
    if (index > 0 && index < 3)
        return string.Format("{0:yyyy-MM-dd HH:mm:ss.fffffff}", field);}
    else
        return field.ToString();
}

// ...

StringBuilder sb = new StringBuilder();
var columnNames = dt.Columns.Cast<DataColumn>().Select(column => "\"" + column.ColumnName.Replace("\"", "\"\"") + "\"").ToArray();
sb.AppendLine(string.Join(",", columnNames));
foreach (DataRow row in dt.Rows)
{
   var fields =   row.ItemArray.Select((field, index) => "\"" + FormatStringByIndex(field, index).Replace("\"", "\"\"") + "\"").ToArray();
   sb.AppendLine(string.Join(",", fields));
}

Upvotes: 5

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73452

If the column contains DateTime type then just do this.

var formatted = ((DateTime)row[1]).ToString("yyyy-MM-dd HH:mm:ss.fffffff");

otherwise you need to convert it to DateTime first, then call DateTime.ToString(format).

Upvotes: 0

Related Questions