Using Linq, get all items from list that are in another List

c# entity-framework linq

Question

I have the following scenario: a list of int: List<int> idsOnly = new List<int>(); and another list of object that should bring all items that their ids matching the list idsOnly

var myList = db.Items.Where(item => idsOnly.Contains(item.ID.Value))
                     .Select(a => new { a.Title })
                     .ToList();

I only need to get the titles from the myList

Any help will be appreciated

1
5
9/26/2012 4:22:22 PM

Accepted Answer

Your code works but it will create the list of anonymous object, not string type

Instead of using (a => new { a.Title }, you just use a => a.Title if you just only want to get the title:

var myList = db.Items.Where(item => idsOnly.Contains(item.ID.Value))
                     .Select(a => a.Title).ToList();
13
9/26/2012 4:22:38 PM

Popular Answer

You can use a Join

var titlesInIdList = from item in db.Items
                     join id in idsOnly
                     on item.ID.Value equals id
                     select item.Title;
var list = titlesInIdList.ToList();


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow