GurdeepS
GurdeepS

Reputation: 67283

Filter collection based on values in another collection

I have an array of ints and a list of objects which contain int IDs.

If the array of ints contains 1,2, 3 etc, I just want to get the objects which contain those IDs (So those with 1, 2, 3, etc).

How could this be done in .NET 3.5?

Thanks

Upvotes: 3

Views: 6434

Answers (3)

Anthony Pegram
Anthony Pegram

Reputation: 126992

DaveShaw's answer is fine if you are dealing with small sequences. If your array of IDs grows larger, a more performant approach would be to load the array into a HashSet<T> and then perform the exact same query, except using the set instead.

var hashset = new HashSet<int>(ints);
var matches = objects.Where(obj => hashset.Contains(obj.Id)); 

For this and other more complicated scenarios, you should also know about Enumerable.Join that matches two sequences based upon keys and yields the desired results.

 var matches = from obj in objects 
               join id in ints
               on obj.Id equals id
               select obj;
 // var matches = objects.Join(ints, obj => obj.Id, id => id, (obj, id) => obj);

Upvotes: 8

Foo42
Foo42

Reputation: 3144

An alternative to the where approach might be something like this:

var ints = new[] {1, 2, 3, };
var matches = ints.Intersect(objects.Select( obj => obj.Id));

This projects the objects to ints, and then performs the Intersect Set operation. Just a different approach.

Upvotes: -1

DaveShaw
DaveShaw

Reputation: 52818

Assuming objects is a list of instances of your class that have an Id property, you can do it like this.

var ints = new[] {1, 2, 3, };
var matches = objects.Where(obj => ints.Contains(obj.Id));

Upvotes: 4

Related Questions