繁体   English   中英

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

[英]Linq to SQL, contains in where clause repeated values

我有一个简单的项目表,称为“项目”:

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

我有一个 Int32 列表,它们是我想显示的项目 ID:

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

对于这个例子 currentItemsCodes 包含 1,2,2,3

目前我有这个 Linq-to-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

我需要返回两个“另一件事”:

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

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

您应该在 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 访问项目的方法

暂无
暂无

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

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