How to use Not In datatable.select

依然范特西╮ 提交于 2019-12-06 01:40:04

问题


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


回答1:


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



回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/26359719/how-to-use-not-in-datatable-select

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