检查键值是否存在于多个 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);

我想获取键值 BoughtById 谁购买了所有三件商品,然后从所有 IGroupings 中删除它们,如果他们没有购买所有三件商品。

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

输出

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

听起来像是 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
*/

要获得每个中的 BoughtById,您需要三组键的交集:

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

boughtAll 现在将视情况而定 IEnumerable<int>IQueryable<int>

然后根据该交集获取要过滤的相应组:

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