3

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.

Sample Output:-

Group 1:- 1 Apple 1 Grapes Group 2:- 2 Tablet 2 Laptop Group 3:- 5 Coke 6 Coke 
2
  • What if item would get into two groups, e.g. 2 - Coke in your example? Commented Oct 29, 2014 at 6:11
  • @MarcinJuraszek - Then CategoryID group should be preferred. Commented Oct 29, 2014 at 6:14

1 Answer 1

3

To add some details to your requirements it seems that you want to do a normal group by on CategoryID. Then, if any groups only contain a single element you want these to be grouped by Fruit. The key of this group will have to contain both a CategoryID and a Fruit. For groups 1 and 2 in your sample data the Fruit property will be the default value for Fruit. For group 3 the CategoryID will be the default value for 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 ----------------+----------------- 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Martin! I was basically looking to group by either CategoryID or Fruits(Whichever matches in the list), and not grouping just by CategoryID. But, the query which you provided is grouping correctly and I am getting the correct output. Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.