0

Let's say I have the following items:

ID      Category        Name

1       Fruit           Banana
2       Car             Mescedes
3       Fruit           Blackberry
4       Fruit           Mango
5       Car             Lexus
6       Fruit           Melon
7       Car             BMW
8       Car             Toyota

I want to group them into Category and take only the first 3 items of each Category. Is it possible?

I expected the output:

ID        Category        Name

1        Fruit           Banana
3        Fruit           Blackberry
4        Fruit           Mango
2        Car             Mescedes
5        Car             Lexus
7        Car             BMW

Any helps would be appreciated!

ByulTaeng
  • 1,269
  • 1
  • 21
  • 40

2 Answers2

4

From head and not tested:

from c in categoryList
group by c.Category into g
let fewItems = g.Take(3).ToList()
return new { Category = g.Key, Items = fewItems }
Euphoric
  • 12,645
  • 1
  • 30
  • 44
0

Lets say you list collection is named as categoryList..

The linq queries to achive what you want is:

categoryList.GroupBy(c=>c.Category).Take(3)
sajoshi
  • 2,733
  • 1
  • 18
  • 22
  • Thanks for ur fast reply. I missed the most important part. The first 3 items of `each category`, not all. – ByulTaeng Mar 24 '11 at 08:25