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

c# entity-framework linq

Question

The situation is as follows: a list of integersList<int> idsOnly = new List<int>(); also, there is another list of objects that need to deliver all things whose ids match the list idsOnly.

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

All I have to do is obtain the titles from myList.

I would appreciate any assistance.

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

Accepted Answer

Your code is functional, however it will produce a list of anonymous objects rather than strings.

rather than utilizing(a => new { a.Title } , you just utilizea => a.Title if you're simply interested in 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 may employ aJoin

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