简体   繁体   English

如何在LINQ中使用SQL IN运算符

[英]How to use SQL IN operator in LINQ

I want to use IN operator in LINQ. 我想在LINQ中使用IN运算符。 I have a SQL query like given below. 我有一个如下所示的SQL查询。 How do i include the where criteria. 我如何包括在哪里标准。

SQL Query SQL查询

SELECT     ServiceId, ServiceName, Rate
FROM         Service
WHERE     (ServiceId IN (1, 2, 3, 4))

LINQ LINQ

string serviceId = "(1,2,3,4,5,6)";

try
{
    using (var context = new DBEntities())
    {
        var query = (from c in context.Service
                     where c.ServiceId == serviceIds     //ServiceId is the primary key
                     select new
                     {
                        serviceId = c.ServiceId,
                        serviceName = c.ServiceName,
                        rate = c.Rate

                     }).ToList();

        GridView1.DataSource = query.ToList();
        GridView1.DataBind();

    }
}
catch (Exception ex)
{
    throw ex;
}

You could use contains of a list, make serviceId a list or array 您可以使用包含列表的内容,将serviceId用作列表或数组

var serviceIds = new int[] { 1, 2, 3, 4, 5, 6 };

try
{
    using (var context = new DBEntities())
    {
        var query = (from c in context.Service
                        where serviceIds.Contains(c.ServiceId)      //ServiceId is the primary key
                        select new
                        {
                            serviceId = c.ServiceId,
                            serviceName = c.ServiceName,
                            rate = c.Rate

                        }).ToList();

        GridView1.DataSource = query.ToList();
        GridView1.DataBind();

    }
}
catch (Exception ex)
{
    throw ex;
}
where serviceId.Contains(c.ServiceId)

I prefer to use Any, there may be some problems while using contains. 我更喜欢使用Any,在使用contains时可能会出现一些问题。

var serviceIds = new int[] { 1, 2, 3, 4, 5, 6 }; var serviceIds = new int [] {1,2,3,4,5,6};

try
{
    using (var context = new DBEntities())
    {
        var query = (from c in context.Service
                        where serviceIds.Any(t=> t.ID == c.ServiceId)
                        select new
                        {
                            serviceId = c.ServiceId,
                            serviceName = c.ServiceName,
                            rate = c.Rate

                        }).ToList();

        GridView1.DataSource = query.ToList();
        GridView1.DataBind();

    }
}
catch (Exception ex)
{
    throw ex;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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