简体   繁体   中英

LINQ to SQL where in (lambda syntax)

Can someone help me with this please? I would like a simple 'where in'. Here's the SQL that does what I want.

select ur.RoleID
from UserRoles ur
where ur.RoleID in (5, 15)

And here's my attempt. The method .IN() doesn't exist obviously, just put my aggrevated thoughts lol.

int roleid;
foreach (data r in dataList) {
    using (DataContext communityContext = new DataContext()) {
        roleid = communityContext.UserRoles
            .Where(x => x.UserID == r.ClientId && x.RoleID.IN(5, 15))
            .Select(x => x.RoleID)
            .First();
    }
}

As you mention In doesn't exist, se .Contains() instead if you have a list, in your case you could also use x.RoleId == 5 || x.RoleId == 15 x.RoleId == 5 || x.RoleId == 15

eg

var allowedRoles = new int[] { 5, 15 };

then in your where clause do:

allowedRoles.Contains(x.RoleID)
var setNumbers = new List<int>() { 5, 15};

communityContext.UserRoles.Where(x => x.UserID == r.ClientId)
                          .Where(x => setNumbers.Contains( x.RoleID ) )
                          ...

HTH

I would rewrite it as...

int roleid;
var allowedRoles = new[] {5, 15};
foreach (data r in dataList) {
    using (DataContext communityContext = new DataContext()) {
        roleid = communityContext.UserRoles
            .First(x=> x.UserID == r.ClientId && allowedRoles.Contains(x.RoleID))
            .RoleID;            
    }
}

Also, I'm not sure why you are creating the datacontext inside the loop. That seems wasteful since the datacontext isn't dependent on the datalist.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM