Bryuk
Bryuk

Reputation: 3345

How to split DataTable into multiple DataTables based on value in 1st Column in c#?

I have the following datatable: enter image description here

I want to split it into List that will contains 3 tables like this: enter image description here

What is the best and the fastest way? I have only loop in my head, but I think this is not the best idea, because my source table contains more than 3k rows and I want to get about 300 sub tables...

Upvotes: 0

Views: 4836

Answers (1)

Bryuk
Bryuk

Reputation: 3345

Thanks for everybody. I've end up with my solution that I combined from your comments=)

// Fill Employee names in each row
string fullName = "";
for (int i = 0; i < dt.Rows.Count; i++)
{
    if (dt.Rows[i][0].ToString() != "")
    {
        fullName = dt.Rows[i][0].ToString();
    }
    else
    {
        dt.Rows[i][0] = fullName;
    }
}

// Split into tables by each employee
List<DataTable> employeesTables = dt.AsEnumerable()
                        .GroupBy(row => row.Field<string>("F1"))
                        .Select(g => g.CopyToDataTable())
                        .ToList();

Upvotes: 1

Related Questions