I want to filter a list by a given List of Ids, that the item should 'be in'
// list is of type List<BaseModel>
// so item is of type BaseModel
// item.Id is of type ushort
// filter.IdIn is of type List<ushort>
List<BaseModel> filtered = (List<BaseModel>)
from item in list
where filter.IdIn.Contains(item.Id)
select item;
This throws the error (translated from german to english by me - silly me installed VisualStudio in german..):
System.InvalidCastException: 'The Object of type
"WhereListIterator`1[JeffData.BaseModel]" can not be converted to
"System.Collections.Generic.List`1[JeffData.BaseModel]" '
Following this answer I've tried changing to
List<BaseModel> filtered = (List<BaseModel>)
from item in list
where filter.IdIn.ToList().Contains(item.Id)
select item;
and
List<BaseModel> filtered = (List<BaseModel>) list.Where(item =>
filter.IdIn.ToList().Contains(item.Id)
);
// with or without ToList()
It will all throw the same error.
When I don't try to Cast it to List,
var filtered = list.Where(item => filter.IdIn.Contains(item.Id));
no error is thrown (because it wont compile) and filtered
will just be a 'WhereListIterator' and I cannot return it
return filtered; // as a List<BaseModel>
Getting back a WhereListIterator made me think I might need to do it the other way round. Don't check if filter.IdIn.Contains(item.Id)
but check if item.Id is in/partof/memberof filter.IdIn
, but this doesn't seem to exist!?
So boiled down: I have a list of items that have an ushort Id. I wanna find the items which Ids are in a List of ushort Ids.