Jeff Giesbrecht
Jeff Giesbrecht

Reputation: 35

How do I create a linq query that gets everything but a specific value

Say I have a linq query select r in db.Roles where r.RoleName DOES NOT contain ("Administrator") select r;

It is the does not contain part that has me confused. I realize I can do that .Contains call but how do you do the opposite?

Thanks!

Update: I found the Exclude method and here is how I used it:

var role = (from r in db.Roles
            orderby r.RoleName
            select r)
           .Except(from r in db.Roles 
                   where r.RoleName == "Administrator" & r.RoleName == "DataEntry" 
                   select r
            );

Upvotes: 2

Views: 647

Answers (2)

mqp
mqp

Reputation: 72015

If you had multiple roles to exclude, you might take a look at the Except function.

Upvotes: 3

JaredPar
JaredPar

Reputation: 755587

Try the following

var query = db.Roles.Where(x => !x.RoleName.Contains("Administrator"));

You can just use the C# not operator ! (exclamation point). Expanded LINQ syntax version

var query = 
  from it in db.Roles
  where !it.RoleName.Contains("Administrator")
  select it;

Upvotes: 9

Related Questions