Reputation: 6159
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
Upvotes: 5
Views: 35737
Reputation: 1
var Result = (from item in db.Items
join id in idsOnly
on item.ID.Value equals id
select new {item.Title}).ToList(); //Here U can return ToArray or ToList()
Upvotes: 0
Reputation: 75326
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();
Upvotes: 15
Reputation: 29000
You can try with (If problem conversion : Convert to int your Id, if is not of int type)
var myList = db.Items.Where(item => (idsOnly.Contains(Convert.ToInt32(item.ID.Value)))).Select(a => a.Title ).ToList();
Without conversion
var myList = db.Items.Where(item => (idsOnly.Contains(item.ID.Value))).Select(a => a.Title ).ToList();
Upvotes: 0
Reputation: 460328
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();
Upvotes: 1
Reputation: 3297
var myList =
(from item in db.Items
where idsOnly.Contains(item.ID.Value)
select item.Title).ToList()
Upvotes: 0