Skip to main content

How to convert Dictionary to a comma separated csv string in c#?

the following function will take the list of dictionary items to a comma separated csv string.

public string ConvertToCSV(List<Dictionary<string, string>> items)
{
    if (!items.Any()) return string.Empty;
    StringBuilder writer = new StringBuilder();
    // Generating Header.
    List<string> headers = items[0].Keys.Select(x => x).OrderBy(x => x).ToList();
    writer.AppendLine(string.Join(", ", headers.Select(h => h)));
    // Generating content.
    foreach (var item in items)
    writer.AppendLine(string.Join(", ", headers.Select(h => item[h])));
    return writer.ToString();
}
 

Comments

  1. This comment has been removed by the author.

    ReplyDelete
  2. Warning! If your data contains comma (,) or quote (") characters, this will not produce the output you want. You can escape a comma by putting the data in quotes, and you can escape a quote literal by doubling it.

    public static string CsvFromDictionaries(
      IEnumerable<IDictionary<string, string>> records)
    {
        var headers = records.FirstOrDefault()?.Keys ?? new string[] { };
        var headerRow = headers.ToDictionary(h => h, h => h);
        var rows = new[] { headerRow }.Concat(records).Select(record =>
        {
            var values = headers.Select(key =>
            {
                var value = record[key] ?? String.Empty;
                value = value.Replace("\"", "\"\"");
                if (value.Contains('"') || value.Contains(','))
                {
                    value = '"' + value + '"';
                }
                return value;
            });
            return String.Join(",", values);
        });
        return String.Join("\n", rows);
    }

    ReplyDelete

Post a Comment

Popular posts from this blog

How to post a dynamic form using json data?

// Post dynamic form using json data   function post(uri, data, method) { // when method not provided use default post method method = method || "post" ;     var form = document.createElement( "form" ); form.setAttribute( "method" , method); form.setAttribute( "action" , uri); for ( var property in data) {   if (params.hasOwnProperty(property)) {     var hiddenField = document.createElement( "input" );     hiddenField.setAttribute( "type" , "hidden" );     hiddenField.setAttribute( "name" , property);     hiddenField.setAttribute( "value" , data[property]);      form.appendChild(hiddenField);   } } document.body.appendChild(form); form.submit(); }

Mapping .NET Data Types to MySQL Data Types

Mapping .NET Data Types to MySQL Data Types .NET Data Types MySQL Data Types System.Boolean boolean, bit(1) System.Byte tinyint unsigned System.Byte[] binary, varbinary, blob, longblob System.DateTime datetime System.Decimal decimal System.Double double System.Guid char(36) System.Int16 smallint System.Int32 int System.Int64 bigint System.SByte tinyint System.Single float System.String char, varchar, text, longtext System.TimeSpan time DateTimeOffset type is not supported.

C# - How to get Property Name and Value of a dynamic object?

C# - Dynamic Object Use the following code to get Name and Value of a dynamic object's property. dynamic d = new { Property1= "Value1", Property2= "Value2"}; var properties = d.GetType().GetProperties(); foreach (var property in properties) {     var PropertyName= property.Name; //You get "Property1" as a result     var PropetyValue= d.GetType().GetProperty(property.Name).GetValue(d, null); //You get "Value1" as a result // you can use the PropertyName and Value here  }