zeencat
zeencat

Reputation: 590

C#, lambda, linq

Say I have an int list that contains a list of ids. I have a linq table and I want to return a particular column but only where the ID of the linq table is equal to any of the ID's in the int list.

So far I have:

dc.tb_References.SelectMany(n => n.ID == ids).ToList();

In sql I would just write:

SELECT Column_Name from Table where ID in (1,2,3,4)

I have been googling but I can't find what I'm looking for. Does anyone have any tips? I would like to stick with lambda expressions.

Upvotes: 0

Views: 1031

Answers (6)

Ufuk Hacıoğulları
Ufuk Hacıoğulları

Reputation: 38468

You can use Contains() method on ID list.

dc.tb_References.Where(item => ids.Contains(item.ID)).ToList();

Upvotes: 5

stay_hungry
stay_hungry

Reputation: 1448

int ids = new int[]{1,2,3,4};
var list =  (from d in dc.tb_References
             where ids. Contains(d.ID)
             select d. Column_Name).ToList();

Upvotes: 0

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236228

To generate IN clause you need to call the Contains method on the collection and pass that method the property of the object you want to search for:

var ids = new int[] { 1, 3 };
var query = from n in dc.tb_References 
            where ids.Contains(n.ID) 
            select n;

Here is generated SQL (from LinqPad):

DECLARE @p0 Int = 1
DECLARE @p1 Int = 3

SELECT [t0].[ID], [t0].[Foo], [t0].[Bar]
FROM [tb_References] AS [t0]
WHERE [t0].[ID] IN (@p0, @p1)

Upvotes: 0

Matthew
Matthew

Reputation: 5222

Use the Where method with the Contains method:

dc.tb_References
    .Where(n => theListOfIds.Contains(n.ID))
    .Select(x => x.Column_Name)
    .ToList();

or you can do:

var query = from item in dc.tb_References
            where theListOfIds.Contains(item.ID)
            select item.Column_Name;

var list = query.ToList();

SelectMany is used to select items from a sub-list and then retun all these ites as a list:

Fruit.Items:   Apple, Pear
Veggies.Items: Carrot, Cabbage

List.Items: Fruit, Veggies

List.Items.SelectMany(x => x.Items)

Result:

Apple, Pear, Carrot, Cabbage

Upvotes: 2

Rob
Rob

Reputation: 10248

Is this the kind of thing you're after?

int[] myIds = {1,4,5,3};
List<int> list = new List<int>();

list.Add(1);
list.Add(5);
list.Add(8);
list.Add(9);
list.Add(10);
list.Add(12);


List<int> select = (from l in list where myIds.Contains(l) select l).ToList();

Upvotes: 0

Likurg
Likurg

Reputation: 2760

Try this

dc.tb_References.Where(n => ids.Contains(n.ID)).ToList();

Upvotes: 4

Related Questions