jpavlov
jpavlov

Reputation: 2261

remove nested values from object in linq

I have an object called copyAgencies which contains a class called Programs, which contains various information pertaining to a program (name, id, ect...).

I am trying to write a foreach loop to remove all programs that do not a match a certain id parameter.
For example, copyAgencies could contain 11 different programs; passing in 3 ids means that the other 8 programs should be removed from the copyAgencies object.

I tried the following code, which fails. Could you help me making it work?

foreach (int id in chkIds)
{
    //copyAgencies.Select(x => x.Programs.Select(b => b.ProgramId == id));
    copyAgencies.RemoveAll(x => x.Programs.Any(b => b.ProgramId != id)); //removes all agencies
}

Upvotes: 1

Views: 1727

Answers (2)

samy
samy

Reputation: 14962

An easy way to filter out values is to avoid removing the values you're not interesting but filtering the ones you're interested in:

var interestingPrograms = Programs.Where(p => chkIds.Contains(p.Id));

In order to apply this to your agencies you can simply enumerate agencies and filter out the Programs property

var chckIds = new List<int>() {1,2,3};
foreach (var a in agencies)
{
    a.Programs = a.Programs.Where(p => chkIds.Contains(p.Id));
}

Upvotes: 0

Racil Hilan
Racil Hilan

Reputation: 25341

If you only have one agency like you said in your comment, and that's all you care about, try this:

copyAgencies[0].Programs.RemoveAll(x => !chkIds.Contains(x.ProgramId));

Upvotes: 1

Related Questions