1

I have an IEnumerable of this type of class ColumnInfo

namespace MyCompany
{
    public class ColumnInfo
    {
        public int Id { get; set; }        
        public string Description { get; set; }
        public int DisplayOrder { get; set; }
        public string ColumnName { get; set; }       
    }
}

In this class I have a ColumnName property that shows me string column names.

I have already a populated DataTable with some columns.

I need to remove columns from the data table that are not in my IEnumerable with property ColumnName. I need in my datatable only the columns that I have listed in the ColumnName property.

4

2 回答 2

3

有几种方法可以给这个皮肤贴皮 - 这里有一个选项:

List<DataColumn> columnsToRemove = new List<DataColumn>();
foreach (DataColumn dc in dt.Columns)
{
    if (list.Any(ci => ci.ColumnName == dc.ColumnName))
    {
        continue;
    }

    columnsToRemove.Add(dc);
}

foreach (DataColumn dc in columnsToRemove)
{
    dt.Columns.Remove(dc);
}
于 2013-10-11T14:43:28.323 回答
2

你可以使用这个 linq 查询:

var columnsToRemove = table.Columns.Cast<DataColumn>()
    .Where(col => !columnInfos.Any(ci => ci.ColumnName == col.ColumnName))
    .ToList();

foreach(DataColumn col in columnsToRemove)
    table.Columns.Remove(col);
于 2013-10-11T14:50:42.080 回答