35

I have a datatable with two columns,

Column 1 = "EmpID"
Column 2 = "EmpName"

I want to query the datatable, against the column EmpID and Empname.

For example, I want to get the values where

(EmpName != 'abc' or EmpName != 'xyz') and (EmpID = 5)
Cœur
  • 37,241
  • 25
  • 195
  • 267
Anuya
  • 8,082
  • 49
  • 137
  • 222

3 Answers3

42

Something like this...

var res = from row in myDTable.AsEnumerable()
where row.Field<int>("EmpID") == 5 &&
(row.Field<string>("EmpName") != "abc" ||
row.Field<string>("EmpName") != "xyz")
select row;

See also LINQ query on a DataTable

Community
  • 1
  • 1
mamoo
  • 8,156
  • 2
  • 28
  • 38
  • missied out, how can i get the count of number of rows returned. Thanks – Anuya Mar 30 '12 at 07:27
  • sorry, i couldnt. I get this error when i convert res.count to Int...{"Specified cast is not valid."}{system.SystemException {System.InvalidCastException} – Anuya Mar 30 '12 at 07:41
  • VB ex: Dim result = From row In myDataTable.AsEnumerable() Where row.Field(Of Integer)("myColumn1") > 0 And row.Field(Of Integer)("myColumn2") > 0 Select row – Brent Sep 25 '14 at 19:36
21

You can do it with Linq, as mamoo showed, but the oldies are good too:

var filteredDataTable = dt.Select(@"EmpId > 2
    AND (EmpName <> 'abc' OR EmpName <> 'xyz')
    AND EmpName like '%il%'" );
Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
Gert Arnold
  • 105,341
  • 31
  • 202
  • 291
16

something like this ? :

DataTable dt = ...
DataView dv = new DataView(dt);
dv.RowFilter = "(EmpName != 'abc' or EmpName != 'xyz') and (EmpID = 5)"

Is it what you are searching for?

Tigran
  • 61,654
  • 8
  • 86
  • 123