Linq to SQL, where子句中包含重复的值

本文关键字:包含重 子句 to SQL where Linq | 更新日期: 2023-09-27 18:12:36

我有一个简单的项目表,名为" items ":

id  description
--  -----------
 1  Something
 2  Another thing
 3  Best thing

我有一个Int32的列表,这是我想显示的项目id:

List<Int32> currentItemsCodes = new List<int>();

本例中currentItemsCodes包含1,2,2,3

当前我有这个sql:

var itemDescriptions = (from a in db.ITEMS
where currentItemsCodes.Contains(a.id)
select new {a.id, a.description});

返回的是:

1,Something
2,Another thing
3,Best thing

我需要返回两个"Another things":

1,Something
2,Another thing
2,Another thing
3,Best thing

或者如果currentItemsCodes是3,3,3,3,我需要4个"Best thing"返回

Linq to SQL, where子句中包含重复的值

您应该在linq中执行内部连接以获得您正在寻找的内容。使用下面的linq查询来完成。

   var itemDescriptions = (from a in db.ITEMS
            join c in currentItemsCodes
                on a.id equals c
            select new {a.id, a.description});

您可以使用join子句:

var itemDescriptions = (from item in db.ITEMS
                       join i in currentItemsCodes on item.id equals i
                       select new
                       {
                           id = item.id,
                           description = item.description
                       }).ToList();

像这样?

var x = db.items;
var itemDescriptions = (from a in currentItemsCodes
select new {a, x[a].description});

在Kris的注释中,用一个方法代替[a],通过id

访问条目