Get filtered data from dataset to datatable

懵懂的女人 提交于 2019-12-06 01:47:06

问题


How can I filter data from dataset to datatable? like the code->

DataRow[] dr = DS.Tables[0]
    .Select("STAGENAME='Develop' AND DEVLAPSEDAYS IS NOT NULL");        

How can I use datatable here?

following code doesn`t reflect changes->

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

Is is possible to remove a column using above filter,like "STAGENAME='Develop' AND DEVLAPSEDAYS IS NOT NULL" + FilteredDataD.column("col_name")... Suppose I have 5 columns display only 4,I can`t remove col_name from my query.Is there a way?

Reply


回答1:


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(); 
}



回答2:


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");


来源:https://stackoverflow.com/questions/10317416/get-filtered-data-from-dataset-to-datatable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!