Search code examples
c#entity-frameworkobjectcsventity

Is there a quick way to convert an entity to .csv file?


at present, I have:

        string outputRow = string.Empty;
        foreach (var entityObject in entityObjects)
        {
            outputRow = entityObject.field1 + "," + entityObject.Field2  etc....
        }

I'm still new to the Entity Framework, is there a quicker way?


Solution

  • Sample code that shows a simple yet powerful way of accomplishing what you want with no need to hard code property names (using reflection):

     /// <summary>
     /// Creates a comma delimeted string of all the objects property values names.
     /// </summary>
     /// <param name="obj">object.</param>
     /// <returns>string.</returns>
     public static string ObjectToCsvData(object obj)
     {
         if (obj == null)
         {
             throw new ArgumentNullException("obj", "Value can not be null or Nothing!");
         }
      
         StringBuilder sb = new StringBuilder();
         Type t = obj.GetType();
         PropertyInfo[] pi = t.GetProperties();
      
         for (int index = 0; index < pi.Length; index++)
         {
             sb.Append(pi[index].GetValue(obj, null));
      
             if (index < pi.Length - 1)
             {
                sb.Append(",");
             }
         }
      
         return sb.ToString();
     }
    

    More on this:

    Objects to CSV

    How can i convert a list of objects to csv

    Are there any CSV readers/writer lib’s in c#

    Writing a CSV file in .net

    LINQ to CSV : Getting data the way you want

    LINQ to CSV library