Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple WHERE clause in Linq

I'm new to LINQ and want to know how to execute multiple where clause. This is what I want to achieve: return records by filtering out certain user names. I tried the code below but not working as expected.

DataTable tempData = (DataTable)grdUsageRecords.DataSource; var query = from r in tempData.AsEnumerable()             where ((r.Field<string>("UserName") != "XXXX") || (r.Field<string>("UserName") != "XXXX"))                                         select r;                  DataTable newDT = query.CopyToDataTable(); 

Thanks for the help in advance!!!

like image 684
Ganesha Avatar asked Mar 24 '09 23:03

Ganesha


People also ask

Can we use multiple where clause in LINQ?

Well, you can just put multiple "where" clauses in directly, but I don't think you want to. Multiple "where" clauses ends up with a more restrictive filter - I think you want a less restrictive one.

How do I select a query in Linq?

LINQ query syntax always ends with a Select or Group clause. The Select clause is used to shape the data. You can select the whole object as it is or only some properties of it. In the above example, we selected the each resulted string elements.

Is in Linq C#?

Language-Integrated Query (LINQ) is the name for a set of technologies based on the integration of query capabilities directly into the C# language. Traditionally, queries against data are expressed as simple strings without type checking at compile time or IntelliSense support.


Video Answer


1 Answers

Well, you can just put multiple "where" clauses in directly, but I don't think you want to. Multiple "where" clauses ends up with a more restrictive filter - I think you want a less restrictive one. I think you really want:

DataTable tempData = (DataTable)grdUsageRecords.DataSource; var query = from r in tempData.AsEnumerable()             where r.Field<string>("UserName") != "XXXX" &&                   r.Field<string>("UserName") != "YYYY"             select r;  DataTable newDT = query.CopyToDataTable(); 

Note the && instead of ||. You want to select the row if the username isn't XXXX and the username isn't YYYY.

EDIT: If you have a whole collection, it's even easier. Suppose the collection is called ignoredUserNames:

DataTable tempData = (DataTable)grdUsageRecords.DataSource; var query = from r in tempData.AsEnumerable()             where !ignoredUserNames.Contains(r.Field<string>("UserName"))             select r;  DataTable newDT = query.CopyToDataTable(); 

Ideally you'd want to make this a HashSet<string> to avoid the Contains call taking a long time, but if the collection is small enough it won't make much odds.

like image 180
Jon Skeet Avatar answered Sep 28 '22 01:09

Jon Skeet