Michael Kniskern
Michael Kniskern

Reputation: 25270

LINQ query not working - C#

The following LINQ query is trying to remove rows from DataTable if "Training" is either in the "Email" or "PreferredName' columns

  IEnumerable<DataRow> query = from rows in returnTable.AsEnumerable()
                               where !rows.Field<string>("Email").Contains("Training") || 
                               !rows.Field<string>("PreferredName").Contains("Training")
                               select rows;

  DataTable dt1 = query.CopyToDataTable<DataRow>();

It is not actually filter the rows from the returnTable variable. What I am doing wrong?

Upvotes: 1

Views: 1699

Answers (2)

Chris Leyva
Chris Leyva

Reputation: 3526

If you want to filter out where both columns do not include "Training", then change the OR (||) to an And (&&).

IEnumerable<DataRow> query = from rows in returnTable.AsEnumerable()
                           where !rows.Field<string>("Email").Contains("Training") && 
                           !rows.Field<string>("PreferredName").Contains("Training")
                           select rows;

Upvotes: 1

p.s.w.g
p.s.w.g

Reputation: 149020

"Email" and "Preferred Name" column DO NOT contain "Training"

Use && instead of ||:

IEnumerable<DataRow> query =
    from rows in returnTable.AsEnumerable()
    where !rows.Field<string>("Email").Contains("Training") &&
          !rows.Field<string>("PreferredName").Contains("Training")
    select rows;

Or thanks to De Morgan's law, this is equivalent to:

IEnumerable<DataRow> query =
    from rows in returnTable.AsEnumerable()
    where !(rows.Field<string>("Email").Contains("Training") ||
            rows.Field<string>("PreferredName").Contains("Training"))
    select rows;

Note that both conditions are wrapped in parentheses, and the entire expression is negated.

Upvotes: 2

Related Questions