score:377

Accepted answer

you need to turn it on its head in terms of the way you're thinking about it. instead of doing "in" to find the current item's user rights in a predefined set of applicable user rights, you're asking a predefined set of user rights if it contains the current item's applicable value. this is exactly the same way you would find an item in a regular list in .net.

there are two ways of doing this using linq, one uses query syntax and the other uses method syntax. essentially, they are the same and could be used interchangeably depending on your preference:

query syntax:

var selected = from u in users
               where new[] { "admin", "user", "limited" }.contains(u.user_rights)
               select u

foreach(user u in selected)
{
    //do your stuff on each selected user;
}

method syntax:

var selected = users.where(u => new[] { "admin", "user", "limited" }.contains(u.user_rights));

foreach(user u in selected)
{
    //do stuff on each selected user;
}

my personal preference in this instance might be method syntax because instead of assigning the variable, i could do the foreach over an anonymous call like this:

foreach(user u in users.where(u => new [] { "admin", "user", "limited" }.contains(u.user_rights)))
{
    //do stuff on each selected user;
}

syntactically this looks more complex, and you have to understand the concept of lambda expressions or delegates to really figure out what's going on, but as you can see, this condenses the code a fair amount.

it all comes down to your coding style and preference - all three of my examples do the same thing slightly differently.

an alternative way doesn't even use linq, you can use the same method syntax replacing "where" with "findall" and get the same result, which will also work in .net 2.0:

foreach(user u in users.findall(u => new [] { "admin", "user", "limited" }.contains(u.user_rights)))
{
    //do stuff on each selected user;
}

score:-15

seriously? you folks have never used

where (t.mytableid == 1 || t.mytableid == 2 || t.mytableid == 3)

score:0

real example:

var tracklist = model.trackinghistory.groupby(x => x.shipmentstatusid).select(x => x.last()).reverse();
list<int> done_step1 = new list<int>() {2,3,4,5,6,7,8,9,10,11,14,18,21,22,23,24,25,26 };
bool isexists = tracklist.where(x => done_step1.contains(x.shipmentstatusid.value)).firstordefault() != null;

score:0

this isn't exactly the in operator, but it might help you get the expected result and maybe a more generic approach (as it allows two collections to be compared) : intersect

here's a working example

var selected = 
  users.where(u => 
    new[] { "admin", "user", "limited" }.intersect(new[] {u.user_rights}).any()
  );
or
var selected = 
  users.where(u => 
    new[] {u.user_rights}.intersect(new[] { "admin", "user", "limited" }).any()
  );

i guess performance should be benchmarked (against the currently accepted answer) to fully validate this solution...

edit :

as gert arnold asked for an example (ef 6) : this piece of code gives me any user whose first and/or last name matches "john" or "doe" :

// get: webusers
public async task<actionresult> index()
{
  var searchednames = new[] { "john", "doe" };

  return 
    view(
      await db
        .webusers
        .where(u => new[] { u.firstname, u.lastname }.intersect(searchednames).any())
        .tolistasync()
    );

  //return view(await db.webusers.tolistasync());
}

score:2

an alternative method to benalabaster answer

first of all, you can rewrite the query like this:

var matches = from users in people
        where users.user_rights == "admin" ||
              users.user_rights == "users" || 
              users.user_rights == "limited"
        select users;

certainly this is more 'wordy' and a pain to write but it works all the same.

so if we had some utility method that made it easy to create these kind of linq expressions we'd be in business.

with a utility method in place you can write something like this:

var matches = ctx.people.where(
        buildorexpression<people, string>(
           p => p.user_rights, names
        )
);

this builds an expression that has the same effect as:

var matches = from p in ctx.people
        where names.contains(p.user_rights)
        select p;

but which more importantly actually works against .net 3.5 sp1.

here is the plumbing function that makes this possible:

public static expression<func<telement, bool>> buildorexpression<telement, tvalue>(
        expression<func<telement, tvalue>> valueselector, 
        ienumerable<tvalue> values
    )
{     
    if (null == valueselector) 
        throw new argumentnullexception("valueselector");

    if (null == values)
        throw new argumentnullexception("values");  

    parameterexpression p = valueselector.parameters.single();

    if (!values.any())   
        return e => false;

    var equals = values.select(value =>
        (expression)expression.equal(
             valueselector.body,
             expression.constant(
                 value,
                 typeof(tvalue)
             )
        )
    );
   var body = equals.aggregate<expression>(
            (accumulate, equal) => expression.or(accumulate, equal)
    ); 

   return expression.lambda<func<telement, bool>>(body, p);
}

i'm not going to try to explain this method, other than to say it essentially builds a predicate expression for all the values using the valueselector (i.e. p => p.user_rights) and ors those predicates together to create an expression for the complete predicate

source: http://blogs.msdn.com/b/alexj/archive/2009/03/26/tip-8-writing-where-in-style-queries-using-linq-to-entities.aspx

score:3

i also tried to work with an sql-in-like thing - querying against an entity data model. my approach is a string builder to compose a big or-expression. that's terribly ugly, but i'm afraid it's the only way to go right now.

now well, that looks like this:

queue<guid> productids = new queue<guid>(products.select(p => p.key));
if(productids.count > 0)
{
    stringbuilder sb = new stringbuilder();
    sb.appendformat("{0}.productid = guid\'{1}\'", entities.products.name, productids.dequeue());
    while(productids.count > 0)
    {
        sb.appendformat(" or {0}.productid = guid\'{1}\'",
          entities.products.name, productids.dequeue());
    }
}

working with guids in this context: as you can see above, there is always the word "guid" before the guid ifself in the query string fragments. if you don't add this, objectquery<t>.where throws the following exception:

the argument types 'edm.guid' and 'edm.string' are incompatible for this operation., near equals expression, line 6, column 14.

found this in msdn forums, might be helpful to have in mind.

matthias

... looking forward for the next version of .net and entity framework, when everything get's better. :)

score:6

this could be the possible way in which you can directly use linq extension methods to check the in clause

var result = _db.companies.where(c => _db.currentsessionvariabledetails.select(s => s.companyid).contains(c.id)).tolist();

score:8

i will go for inner join in this context. if i would have used contains, it would iterate 6 times despite if the fact that there are just one match.

var desirednames = new[] { "pankaj", "garg" }; 

var people = new[]  
{  
    new { firstname="pankaj", surname="garg" },  
    new { firstname="marc", surname="gravell" },  
    new { firstname="jeff", surname="atwood" }  
}; 

var records = (from p in people join filtered in desirednames on p.firstname equals filtered  select p.firstname).tolist(); 

disadvantages of contains

suppose i have two list objects.

list 1      list 2
  1           12
  2            7
  3            8
  4           98
  5            9
  6           10
  7            6

using contains, it will search for each list 1 item in list 2 that means iteration will happen 49 times !!!

score:21

this should suffice your purpose. it compares two collections and checks if one collection has the values matching those in the other collection

fea_features.where(s => selectedfeatures.contains(s.feaid))

Related Query