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

2k Views Asked by At
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]
2

There are 2 best solutions below

0
On BEST ANSWER

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));
0
On

Sounds like a job for Enumerable.Intersect():

int[] id1 = { 44, 26, 92, 30, 71, 38 };
int[] id2 = { 39, 59, 83, 47, 26, 4, 30 };

IEnumerable<int> both = id1.Intersect(id2);

foreach (int id in both)
  Console.WriteLine(id);

/*
  This code produces the following output:

  26
  30
*/