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 ----------------+-----------------
2 - Cokein your example?