簡體   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