score:1

Accepted answer

Let's do this step by step and then we can merge operations where necessary.

I want to return a list of WorksiteGroup with the full structure above where IsDiscontinued is false

source.Where(e => !e.IsDiscontinued);

and have an ActiveState where StateAbbrev matches any of the filter criteria (states[])

now let's take the previous pipeline and chain this criterion into it.

source.Where(e => !e.IsDiscontinued)
      .Where(e => e.ActiveStates.Any(a => states.Contains(a.StateAbbrev)))

and IsDiscountApplied is true for that state.

source.Where(e => !e.IsDiscontinued)
      .Where(e => e.ActiveStates.Any(s => states.Contains(s.StateAbbrev) && s.IsDiscountApplied));

for efficiency let's swap the Contains call to be after s.IsDiscountApplied e.g.

source.Where(e => !e.IsDiscontinued)
      .Where(e => e.ActiveStates.Any(s => s.IsDiscountApplied && states.Contains(s.StateAbbrev)));

score:1

You can try this using Linq:

  string[] states = new string[] { "abbrev1", "abbrev2" };

  var list = new List<WorksiteGroup>();

  var item = new WorksiteGroup();
  item.Name = "Test1";
  item.IsDiscontinued = false;
  var subitem = new WorksiteGroupState();
  subitem.IsDiscountApplied = true;
  subitem.StateAbbrev = "abbrev1";
  item.ActiveStates.Add(subitem);
  list.Add(item);

  item = new WorksiteGroup();
  item.Name = "Test2";
  item.IsDiscontinued = true;
  subitem = new WorksiteGroupState();
  subitem.IsDiscountApplied = true;
  subitem.StateAbbrev = "abbrev1";
  item.ActiveStates.Add(subitem);
  list.Add(item);

  var result = list.Where(wg => wg.IsDiscontinued == false
                             && wg.ActiveStates.Where(state => state.IsDiscountApplied == true
                                                            && states.Contains(state.StateAbbrev)).Any());

  foreach ( var value in result )
    Console.WriteLine(value.Name);

  Console.ReadKey();

You can play with items and add more to see results.

score:0

sudo-code but would something like below work, im sure you could do this is one line but


var worksiteGroup = Populate();

var filteredWorkSiteGroup = worksiteGroup .Where(x=>x.IsDiscontinued == false);
filteredWorkSiteGroup.ActiveStates = filteredWorkSiteGroup.ActiveStates
                                     .Where(x=> states.Contains(x.StateAbbrev)
                                         && x.IsDiscountApplied == true);




Related Articles