Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 584
Alex Avatar asked Sep 26 '12 08:09

Alex


1 Answers

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();
like image 73
cuongle Avatar answered Sep 27 '22 21:09

cuongle