检查多个 IGrouping 中是否存在键值,如果不存在,则将其删除

本文关键字:如果不 如果 不存在 删除 键值 IGrouping 存在 是否 检查 | 更新日期: 2023-09-27 17:56:53

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]

检查多个 IGrouping 中是否存在键值,如果不存在,则将其删除

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

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

购买所有现在将视情况而定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));

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