When working with large datasets in C#, it is often necessary to export the data to a file format that is easy to read and manipulate. One of the most common formats used for data exchange is CSV (Comma Separated Values). In this article, we will learn how to convert a List of objects to a CSV file in C# using .NET Core, with practical examples. Whether you're working on a small project or large-scale application, this guide will show you how to handle CSV exportation effectively.
What is CSV and Why Use It?
CSV stands for Comma Separated Values, which is a simple text format that stores tabular data. It is commonly used because it is:
- Human-readable: Data in CSV files is easy to read and can be opened using any text editor or spreadsheet software like Microsoft Excel or Google Sheets.
- Lightweight: CSV files are compact and can handle large amounts of data without using too much storage.
- Interoperable: CSV is widely supported across different programming languages, databases, and applications.
Prerequisites
Before we dive into the coding, make sure you have:
- .NET Core or .NET 5/6 installed.
- Visual Studio or Visual Studio Code for writing and testing the code.
- Basic understanding of C# and object-oriented programming.
If you're new to C# or need help with DataTables or exporting data in general, here are a few helpful articles:
- C# DataTable to CSV Example: A Step-by-Step Guide
- Exporting Data to CSV in ASP.NET MVC Using Entity Framework
Convert List of Objects to CSV in C#
To demonstrate how to convert a List to CSV in C#, we will create a simple List of Objects representing some basic data (e.g., employee records). We will then export this data to a CSV file using C# in .NET Core.
Step 1: Define a Class for the Data
First, we need to create a class to represent the data structure that will be stored in the list.
public class Employee { public int Id { get; set; } public string Name { get; set; } public string Position { get; set; } public decimal Salary { get; set; } }
Here, we have a basic Employee
class with Id
, Name
, Position
, and Salary
.
Step 2: Create a List of Objects
Now that we have our Employee
class, let's create a List<Employee>
and populate it with some sample data.
List<Employee> employees = new List<Employee> { new Employee { Id = 1, Name = "Nikunj Satasiya", Position = "Technology Lead", Salary = 75000 }, new Employee { Id = 2, Name = "John Doe", Position = "Software Engineer", Salary = 65000 }, new Employee { Id = 3, Name = "Jane Smith", Position = "Product Manager", Salary = 90000 } };
Step 3: Convert List to CSV
Now that we have our list, we will write a method to convert this list to a CSV file. We'll use StringWriter
to handle the output stream.
using System.Globalization; using System.IO; public static void ConvertListToCsv(List<Employee> employees, string filePath) { var csv = new StringWriter(); var csvWriter = new CsvHelper.CsvWriter(csv, CultureInfo.InvariantCulture); // Write the header csvWriter.WriteHeader<Employee>(); csvWriter.NextRecord(); // Write the records csvWriter.WriteRecords(employees); // Write to a file File.WriteAllText(filePath, csv.ToString()); }
In this code:
- We use
CsvHelper
to simplify the CSV writing process. You can install theCsvHelper
package via NuGet in your project. - We write the header and records, followed by saving the CSV content to a file.
Step 4: Call the Method and Export Data
Finally, call the ConvertListToCsv
method to convert the employees
list to a CSV file.
ConvertListToCsv(employees, "employees.csv");
This will generate a CSV file named employees.csv
in your application's directory, with the following content:
Id,Name,Position,Salary 1,Nikunj Satasiya,Technology Lead,75000 2,John Doe,Software Engineer,65000 3,Jane Smith,Product Manager,90000
Advantages of Converting List to CSV
Converting a List to CSV in C# has several benefits, especially when working with large datasets or sharing data across different platforms:
- Data Sharing: CSV is a common format for sharing data between applications and users.
- Excel Compatibility: The generated CSV file can easily be opened in Excel for further analysis.
- Easy to Parse: Since CSV is plain text, it can be easily parsed by other programming languages or tools.
Handling Complex Data Types
In some cases, your list might contain more complex data types (e.g., nested objects, lists within objects). You can customize the CsvHelper
library to handle these scenarios.
For example, if the Employee
class had a nested Department
object, you could customize the CSV writing process to flatten the structure.
Related Articles
- Convert List of Object to CSV Using C#
- C# List to CSV with Example
- Export Data to CSV File Using ASP.NET MVC
Conclusion
Converting a List to CSV in C# is a straightforward task that can be accomplished with the help of libraries like CsvHelper
. Whether you're exporting employee data or handling more complex datasets, CSV remains one of the best options for data exchange.
With the steps outlined in this guide, you can now easily export your lists to CSV files in .NET Core, and integrate this functionality into your applications. Make sure to customize the process based on your specific needs, whether it’s for simple or complex data structures.