@gal mor , Welcome to Microsoft Q&A, I recommend that you could convert your current csv to many datatables group by Company_ID, then you could convert these datatables to csv files.
Here is a code example you could refer to.
static void Main(string[] args)
{
var dt = ConvertCSVtoDataTable("test.csv");
var result = from rows in dt.AsEnumerable()
group rows by rows["Company_ID"]
into grp
select grp;
foreach (var item in result)
{
DataTable newdt = item.CopyToDataTable();
StringBuilder sb = new StringBuilder();
IEnumerable<string> columnNames = newdt.Columns.Cast<DataColumn>().
Select(column => column.ColumnName);
sb.AppendLine(string.Join(",", columnNames));
foreach (DataRow row in newdt.Rows)
{
IEnumerable<string> fields = row.ItemArray.Select(field => field.ToString());
sb.AppendLine(string.Join(",", fields));
}
File.WriteAllText("CompanyID" + item.Key + ".csv", sb.ToString());
}
}
public static DataTable ConvertCSVtoDataTable(string strFilePath)
{
DataTable dt = new DataTable();
using (StreamReader sr = new StreamReader(strFilePath))
{
string[] headers = sr.ReadLine().Split(',');
foreach (string header in headers)
{
dt.Columns.Add(header);
}
while (!sr.EndOfStream)
{
string[] rows = sr.ReadLine().Split(',');
DataRow dr = dt.NewRow();
for (int i = 0; i < headers.Length; i++)
{
dr[i] = rows[i];
}
dt.Rows.Add(dr);
}
}
return dt;
}
Hope my solution could help you.
Best Regards,
Jack
If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.