1

I want to remove the columns that have not a certain name. I have been searching but can't find something that can help me.

This is what I am trying:

DataColumnCollection columns = dtExcelInforme.Columns;
foreach (DataColumn col in columns)
            {
                if ((col.ColumnName != "Code") || (col.ColumnName != "Denomination"))
                {
                    dtExcelInforme.Columns.Remove(col);
                }
            }

But this doesn't work because I am modifying the collection of columns.

How can I do it? Thanks in advance!

LuckWallace
  • 113
  • 10
  • create new one with the desired columns? – ilkerkaran Jan 07 '20 at 16:58
  • Just call `dtExcelInforme.Columns.Remove` ... – Trevor Jan 07 '20 at 16:58
  • @Çöđěxěŕ is what I have seen but doesn't help me and the code you put is what I am trying – LuckWallace Jan 07 '20 at 17:05
  • @LuckWallace so you couldn't put the names in a list, loop through that list and remove them by name...? There's a solution there that *would [help](https://stackoverflow.com/a/58115639/1797425)*. – Trevor Jan 07 '20 at 17:07
  • @Çöđěxěŕ there's something similar, but what I want to do is remove columns that No contains a name. – LuckWallace Jan 07 '20 at 17:11
  • @LuckWallace so why not put all the one's that you don't want removed in the list and then go through that list, I don't see what the issue is. – Trevor Jan 07 '20 at 17:13
  • @Çöđěxěŕ is there a example of code to do this? – LuckWallace Jan 07 '20 at 17:22
  • 1
    @LuckWallace do this `dtExcelInforme.Columns.Cast().Where(col => col.ColumnName != "Code" && col.ColumnName != "Denomination")).ToList() .ForEach(col => dtExcelInforme.Columns.Remove(col.ColumnName));` it's a `linq` version and all you need. – Trevor Jan 07 '20 at 17:40
  • Thank you for your help @Çöđěxěŕ but this doesn't work :( – LuckWallace Jan 08 '20 at 08:30

0 Answers0