Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trim whitespace from DataTable cells with Linq

Tags:

linq

This piece of code works to trim all spaces in each datacell of each datarow. How can I get this code:

var dataRows = dataTable.AsEnumerable();
foreach (var row in dataRows)
{
     var cellList = row.ItemArray.ToList();
     row.ItemArray = cellList.Select(x => x.ToString().Trim()).ToArray();
}

into one line of code so I don't have to loop through each row? Something like this but it doesn't work:

dataTable.AsEnumerable().Select(y => y.ItemArray.ToList()).Select(x => x.ToString().Trim());
like image 351
zeb ula Avatar asked Sep 06 '25 03:09

zeb ula


2 Answers

If you love LINQish stype:

  dataTable.AsEnumerable().ToList()
        .ForEach(row =>
        {
            var cellList = row.ItemArray.ToList();
            row.ItemArray = cellList.Select(x => x.ToString().Trim()).ToArray();
        });
like image 97
cuongle Avatar answered Sep 11 '25 00:09

cuongle


With linq you can't change item values finally you should run for loop (or foreach) to change fields value.

like image 26
Saeed Amiri Avatar answered Sep 11 '25 02:09

Saeed Amiri