Linq to Entities-SQL"IN"条款 [英] Linq to Entities - SQL "IN" clause

查看:48
本文介绍了Linq to Entities-SQL"IN"条款的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在T-SQL中,您可以进行类似以下查询:

In T-SQL you could have a query like:

SELECT * FROM Users WHERE User_Rights IN ("Admin", "User", "Limited")

您将如何在LINQ to Entities查询中复制它?甚至有可能吗?

How would you replicate that in a LINQ to Entities query? Is it even possible?

推荐答案

您需要从思考的角度出发.您不是要输入"以在一组预定义的适用用户权限中查找当前项目的用户权限,而是要询问一组预定义的用户权限是否包含当前项目的适用值.这与在.NET的常规列表中找到项目的方式完全相同.

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.

有两种使用LINQ进行此操作的方法,一种使用查询语法,另一种使用方法语法.本质上,它们是相同的,并且可以根据您的喜好互换使用:

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;
}

在这种情况下,我个人的偏爱可能是方法语法,因为我无需分配变量,而是可以通过如下匿名调用进行foreach

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;
}

从语法上看,这看起来更复杂,您必须了解lambda表达式或委托的概念才能真正弄清楚发生了什么,但是如您所见,这会使代码浓缩很多.

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.

另一种方法甚至不使用LINQ,您可以使用相同的方法语法将"where"替换为"FindAll",并获得相同的结果,这在.NET 2.0中也适用:

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;
}

这篇关于Linq to Entities-SQL"IN"条款的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆