Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return only values contained in list C#

Tags:

c#

.net

list

linq

I have a List<int> ListOfIDs containing some numbers which are IDs.

I have a List<CustomClass> ListOfObjects containing some objects, which properties reflecting their IDs.

I've searched high and low for a Linq query that will allow me to return from my List a sublist of only those objects which have an ID that is contained within the List.

My attempt does not compile and I cannot seem to correct the syntax :

List<CustomClass> SubList = ListOfObjects.Where(ListOfIDs.Contains(p => p.ID))

Thanks very much.

like image 294
Simon Kiely Avatar asked Apr 10 '26 13:04

Simon Kiely


2 Answers

I think you want to do like this?

List<CustomClass> SubList = ListOfObjects
        .Where(obj => ListOfIDs.Contains(obj.ID))
        .ToList();
like image 186
Jonas W Avatar answered Apr 12 '26 03:04

Jonas W


I think this is what you need:

List<CustomClass> SubList = ListOfObjects.Where(p => ListOfIDs.Contains(p.ID)).ToList();

Don't forget to call ToList() in the end.

Also consider using HashSet for ListOfIDs, because complexity of Contains operation is just O(1). But, well it depends on how much data you have.

like image 27
Andriy Buday Avatar answered Apr 12 '26 02:04

Andriy Buday