0
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]
  • 3
    `IGrouping` is a read-only API. You can't *remove* anything. You can create a new collection of the values that are in all three groups, if you want. – Servy Jun 18 '15 at 15:05

2 Answers2

1

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
*/
Erik Philips
  • 53,428
  • 11
  • 128
  • 150
1

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));
Jon Hanna
  • 110,372
  • 10
  • 146
  • 251