7

I have a DataTable (Ado.Net) with column 'Status'. This column holds the values (in each records)

['Red','Green','Blue','Yellow','White','OtherColors']

I want to select all the rows which status value not Red,Green,Blue

What the kind of filter expression to use to select data with my proposed criteria. So i want to achive some thing like we used in sql query ( WHERE Status NOT IN ('Red','Green','Blue')

NB:This project is running .NET 2.0 i cant use linq

3 Answers 3

18

I have tested it, it works as desired:

DataRow[] filtered = tblStatus.Select("Status NOT IN ('Red','Green','Blue')");

The resulting DataRow[] contains only DataRows with OtherColors, Yellow and White.

If you could use LINQ i'd prefer that:

string[] excludeStatus = {"Red","Green","Blue"};
var filteredRows = tblStatus.AsEnumerable()
    .Where(row => !excludeStatus.Contains(row.Field<string>("Status")));
6

Without Linq you can use the rowfilter of a DataView like this

public DataTable GetFilteredData(DataTable table, string[] filterValues)
{
    var dv = new DataView(table);
    var filter = string.join("','", filterValues);
    dv.RowFilter = "Status NOT IN ('" + filter + "')";
    return dv.ToTable();
}
1

Supposing your datatable is part of a typed dataset you can use Linq to datasets, from which you could something like:

var records = 
      from record in datatable
      where !record.Status.Contains('Red','Green','Blue')
      select record;

Even if you don't have a typed dataset Linq to datasets is your answer. You would need to some casting, but not to difficult.

1
  • 1
    This project is running .NET 2.0 i cant use linq Oct 14, 2014 at 11:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.