我想在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;
}
答案 0 :(得分:3)
您可以使用列表的包含,使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;
}
答案 1 :(得分:1)
where serviceId.Contains(c.ServiceId)
答案 2 :(得分:1)
我更喜欢使用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;
}