I have list of objects of a class for example:
class MyClass
{
string id,
string name,
string lastname
}
so for example: List<MyClass> myClassList;
and also I have list of string of some ids, so for example:
List<string> myIdList;
Now I am looking for a way to have a method that accept these two as paramets and returns me a List<MyClass>
of the objects that their id
is the same as what we have in myIdList
.
NOTE: Always the bigger list is myClassList
and always myIdList
is a smaller subset of that.
How can we find this intersection?
So you're looking to find all the elements in myClassList
where myIdList
contains the ID? That suggests:
var query = myClassList.Where(c => myIdList.Contains(c.id));
Note that if you could use a HashSet<string>
instead of a List<string>
, each Contains
test will potentially be more efficient - certainly if your list of IDs grows large. (If the list of IDs is tiny, there may well be very little difference at all.)
It's important to consider the difference between a join and the above approach in the face of duplicate elements in either myClassList
or myIdList
. A join will yield every matching pair - the above will yield either 0 or 1 element per item in myClassList
.
Which of those you want is up to you.
EDIT: If you're talking to a database, it would be best if you didn't use a List<T>
for the entities in the first place - unless you need them for something else, it would be much more sensible to do the query in the database than fetching all the data and then performing the query locally.
See more on this question at Stackoverflow