jim
jim

Reputation: 27426

Linq Select Subset of master list

I have a master list of complex objects.

I have a list of int ids that I need to select the corresponding complex object out of the master list.

this doesn't work

MasterListofComplexObj.Where(u => MasterListofComplexObj.Select(i => i.Id).Contains(ChildListofIntIds));

any help would be appreciated.

Upvotes: 8

Views: 25350

Answers (4)

Marius
Marius

Reputation: 9674

This will probably work as well:

double[] numbers1 = { 2.0, 2.0, 2.1, 2.2, 2.3, 2.3, 2.4, 2.5 };
double[] numbers2 = { 2.2 };

var isNumberTwoSubsetOfNumberOne = !numbers2.Except(numbers1).Any();

Upvotes: 0

Mikeb
Mikeb

Reputation: 6361

The other more general thing to look into would be Join:

var results = MasterList.Join(ChildList, (m => m.Id), (c => c), ((m,c) => m));

I believe, but can't back up with citation or experimental data, that Join would be faster than the Where -> Contains piece.

Upvotes: 1

foson
foson

Reputation: 10227

var results = from obj in MasterListofComplexObj
    where ChildListofIntIds.Contains(obj.Id)
    select obj;

This is an IEnumerable. You may want to .FirstOrDefault() it to get one object.

Translates to MasterListofComplexObj.Where(item => ChildListofIntIds.Contains(item.Id))

No select necessary if you want the object itself and not one of its properties.

Upvotes: 1

BrokenGlass
BrokenGlass

Reputation: 160982

This should work:

var results = MasterListofComplexObj.Where(u => ChildListofIntIds.Contains(u.Id));

Upvotes: 25

Related Questions