Get filtered data from dataset to datatable

 ̄綄美尐妖づ 提交于 2019-12-04 07:09:40

Try using LINQ instead:

var table = DS.Tables[0].AsEnumerable().Where(
    r => r.Field<string>("STAGENAME") == "Develop" && r.Field<int?>("DEVLAPSEDAYS").HasValue).AsDataView().ToTable();

EDIT Changed AsDataView to AsDataView() for syntactical accuracy.
EDIT Provided .NET 2.0 compatible solution

DataTable table = DS.Tables[0];
if (table.Rows.Count > 0)
{
    table.DefaultView.RowFilter = "STAGENAME = 'DEVELOP' AND DEVLAPSEDAYS IS NOT NULL";
    table = table.DefaultView.ToTable(); 
}

You could write an extension method (using C# 3) like follows:

public static DataTable Filter(this DataTable dataTable, string selectFilter)
{
    var filteredTable = dataTable.Clone();
    var rows = dataTable.Select(selectFilter).ToList();
    rows.ForEach(filteredTable.ImportRow);
    return filteredTable;
}

Then use it like follows:

DataTable dataTable = DS.Tables[0]
    .Filter("STAGENAME='Develop' AND DEVLAPSEDAYS IS NOT NULL");

Update, since you said you are using C# 2.0 (and thus extension methods and LINQ aren't an option) you could use this instead:

public static DataTable GetFilteredTable(
    DataTable sourceTable, string selectFilter)
{
    var filteredTable = sourceTable.Clone();
    var rows = sourceTable.Select(selectFilter);
    foreach (DataRow row in rows)
    {
        filteredTable.ImportRow(row);
    }
    return filteredTable;
}

DataTable dataTable = GetFilteredTable(
    DS.Tables[0], "STAGENAME='Develop' AND DEVLAPSEDAYS IS NOT NULL");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!