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

时间:2015-06-18 15:03:55

标签: c# igrouping

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]

输出

<com.nhaarman.listviewanimations.itemmanipulation.DynamicListView
        android:id="@+id/dynamiclistview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

要获得每个中你想要三组密钥交集的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));