简体   繁体   English

GroupBy LINQ中的两个属性之一

[英]GroupBy either of two properties in LINQ

I know its easy to group objects by two properties but I was wondering is it possible to Group by either of two properties? 我知道它很容易通过两个属性对对象进行分组,但我想知道是否可以通过两个属性中的任何一个进行分组? Probably below example will make it more clear:- 可能下面的例子会更清楚: -

Suppose I have this table:- 假设我有这张桌子: -

CategoryID        Fruit
-------------------------
1                 Apple
1                 Grapes
2                 Tablet
2                 Laptop
5                 Coke
6                 Coke

Now, i want to group this data either if CategoryIds are same or Fruits are same. 现在,如果CategoryIds相同或者Fruit相同,我想将这些数据分组。

Sample Output:- 样本输出: -

Group 1:-
1          Apple
1          Grapes

Group 2:-
2          Tablet
2          Laptop

Group 3:-
5          Coke
6          Coke

To add some details to your requirements it seems that you want to do a normal group by on CategoryID . 要根据您的要求添加一些细节,您似乎希望通过CategoryID执行常规组。 Then, if any groups only contain a single element you want these to be grouped by Fruit . 然后,如果任何组只包含一个元素,您希望这些元素按Fruit分组。 The key of this group will have to contain both a CategoryID and a Fruit . 该组的关键必须包含CategoryIDFruit For groups 1 and 2 in your sample data the Fruit property will be the default value for Fruit . 对于集团在您的样本数据1和2中的Fruit属性将是默认值Fruit For group 3 the CategoryID will be the default value for CategoryID . 对于第3组的CategoryID将成为默认值CategoryID

You can perform this computation by doing two nested groupings and then unwrapping the inner grouping again: 您可以通过执行两个嵌套分组然后再次展开内部分组来执行此计算:

var groupedItems = items
  .GroupBy(item => item.CategoryID)
  .GroupBy(
    inner => inner.Count() > 1
      ? new { CategoryID = inner.Key, Fruit = default(String) }
      : new { CategoryID = default(Int32), inner.First().Fruit }
  )
  .Select(
    outer => outer.Count() == 1
      ? new { outer.Key, Items = outer.First().ToList() }
      : new { outer.Key, Items = outer.Select(inner => inner.First()).ToList() }
  );

Given this input 鉴于此输入

var items = new[] {
  new { CategoryID = 1, Fruit = "Apple" },
  new { CategoryID = 1, Fruit = "Coke" },
  new { CategoryID = 2, Fruit = "Tablet" },
  new { CategoryID = 2, Fruit = "Coke" },
  new { CategoryID = 5, Fruit = "Coke" },
  new { CategoryID = 6, Fruit = "Coke" }
};

you get this output 你得到这个输出

Key             |Items
----------------+-----------------
CategoryId Fruit|CategoryID Fruit
----------------+-----------------
1          null |1          Apple
                |1          Coke
----------------+-----------------
2          null |2          Tablet
                |2          Coke
----------------+-----------------
0          Coke |5          Coke
                |6          Coke
----------------+-----------------

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM