Search code examples
c#igrouping

Check if key value exists in multiple IGrouping and remove if they don't


var boughtApples = apples.GroupBy(x => BoughtById);
var boughtCoconuts = coconuts.GroupBy(x => x.BoughtById);
var boughtOranges  = oranges.GroupBy(x => x.BoughtById);

I want to get the key values BoughtById who bought all three items and then remove them if from all IGroupings if the haven' bought all three.

boughtApples   = [1,3,4,5]
boughtCoconuts = [1,2,4,9]
boughtOranges  = [6,3,4,10]

OUTPUT

boughtApples   = [4]
boughtCoconuts = [4]
boughtOranges  = [4]

Solution

  • To just get the BoughtById that is in each you want the intersection of the three sets of keys:

    var boughtAll = boughtApples.Select(gr => gr.Key)
      .Intersect(boughtCoconuts.Select(gr => gr.Key))
      .Intersect(boughtOranges.Select(gr => gr.Key));
    

    boughtAll will now be an IEnumerable<int> or IQueryable<int> as appropriate.

    To then get the corresponding groups you want to filter based on that intersection:

    boughtApples = boughtApples.Where(grp => boughtAll.Contains(grp.Key));
    boughtCoconuts = boughtCoconuts.Where(grp => boughtAll.Contains(grp.Key));
    boughtOranges= boughtOranges.Where(grp => boughtAll.Contains(grp.Key));