【问题标题】:How to use SQL IN operator in LINQ如何在 LINQ 中使用 SQL IN 运算符
【发布时间】:2014-01-05 16:49:19
【问题描述】:

我想在 LINQ 中使用 IN 运算符。我有一个如下所示的 SQL 查询。我如何包含 where 条件。

SQL 查询

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

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

【问题讨论】:

  • 使用集合和.Contains() 方法。

标签: c# asp.net linq lambda


【解决方案1】:

您可以使用包含列表,将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;
}

【讨论】:

  • 谢谢@MichaC。我收到一个错误“错误 8 'string[]' 不包含 'Contains' 的定义和最佳扩展方法重载 'System.Linq.Queryable.Contains(System.Linq.IQueryable, TSource) ' 有一些无效参数"
  • 再次感谢@MichaC 的宝贵时间。
【解决方案2】:
where serviceId.Contains(c.ServiceId)

【讨论】:

    【解决方案3】:

    我更喜欢使用 Any,使用 contains 时可能会出现一些问题。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多