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

时间:2015-09-14 15:07:54

标签: c# linq-to-sql

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

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

我需要返回两个&#34;另一个&#34;:

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

或者如果currentItemsCodes是3,3,3,3我需要4 x&#34;最好的东西&#34;返回

3 个答案:

答案 0 :(得分:3)

You should do a inner join in linq to get what you are looking for. Use the below linq query to do that.

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

答案 1 :(得分:2)

You can use a join clause for that:

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();

答案 2 :(得分:0)

Something like this?

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

As in Kris's comments substitute for [a] a method to access the items by id