0

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.

Jeff
  • 6,895
  • 1
  • 15
  • 33

1 Answers1

2

Not sure about WhereListIterator (not sure if that's part of the translation)

I'd expect the Where() to return an IEnumerable which would not cast to a list.

that's where ToList() will resolve the enumerable for you though.

var filtered = list.Where(item => filter.IdIn.Contains(item.Id)).ToList();

or if you prefer:

var filtered = (from item in list
              where filter.IdIn.ToList().Contains(item.Id)
              select item).ToList();