views:

86

answers:

3

Hi,

I have a list with multiple class that contain a Property that is an Integer (Id).

I have a List of Integer too.

Now, I would like to trim the List of my object to only those class that has the Property in the list of the integer.

Example:

List of MyObject
[MyObjectA].Id = 1
[MyObjectB].Id = 2
[MyObjectC].Id = 3
[MyObjectD].Id = 4

List of Integer
1
2

Final list should be 
[MyObjectA]
[MyObjectB]

How can I do it?

+6  A: 

You could use contains:

var finalList = originalList.Where(x => idList.Contains(x.Id)).ToList();

Or a join:

var finalList = (from entry in originalList
                join id in idList on entry.Id equals id
                select entry).ToList();
Jon Skeet
did you mean entry.Id instead of x.Id? (in case of using join)
shahkalpesh
I like solution 1 the best. The joins are nice, but I like the readability of the first one better.
David Basarab
@shahkalpesh: Fixed, thanks. @Longhorn213: The second one will be significantly quicker if idList ends up being very big. It basically builds a hash map instead of doing a linear scan for every entry.
Jon Skeet
This is what I needed. Thx
Daok
A: 

How about:

list.RemoveAll(x => list2.IndexOf(x.Id) >= 0);
Chris Marisic
A: 

This should do it:

// Assume objList is IEnumerable<MyObject> and intList is IEnumerable<int>.
IEnumerable<MyObject> intersection =
  from obj in objList
    join i in intList on obj.Id equals i
  select obj

Mind you, if multiple objects have the same id, or the id is listed multiple times in the list and one object corresponds to it, the object will show up more than once in the resultant list.

I think the group is better for larger lists, as some of the other solutions will iterate over the lists multiple times to search for the corresponding object.

casperOne