here is the source code
table.Columns.Cast<DataColumn>().ToList().ForEach(col => header.Add(col.ColumnName));
Why is Cast used?
because it allows you to handle DataColumnCollection elements as a DataColumn not an object.
Why is ToList used?
because it converts your IEnumerable to List and allows you to call ForEach , because this function is a special method that exists in the List class.
Why is ForEach used?
because it allows you to do what you want for each item in the list (in your case, it adds the column name of each column to another list ( header )).
Simplified version:
Now suppose you want to add column names to the header , where they begin with "Student", you can write something like this
DataTable table = new DataTable(); List<string> header = new List<string>(); foreach (DataColumn col in table.Columns) { if (col.ColumnName.StartsWith("Id"))
you can also use this
table.Columns.Cast<DataColumn>() .ToList() .ForEach(col => { if (col.ColumnName.StartsWith("Id")) header.Add(col.ColumnName) });
or
var headers = table.Columns.Cast<DataColumn>() .Where(col => col.ColumnName.StartsWith("Id")) .Select(col => col.ColumnName); header.AddRange(headers);
source share