Ali Avcı
Ali Avcı

Reputation: 1301

C# LINQ Take limited results per grouped

I have list that includes class named 'ID', 'Name' and 'Category'. There are 6 item in list.

List<MyData> list = 
{
    {0, "John", "Police"}, 
    {1,"Michael", "Police"},
    {2,"Alice", "Police"}, 
    {3, "Ferdinand", "Thief"}, 
    {4, "Jocas", "Thief"}, 
    {5, "Connor", "Thief"}
};

I wanna list them with limited quantity per group by 'Category' with LINQ.

Example : I want list 2 item for each 'Cateogory'. Listed should be below :

John Police

Michael Police

Ferdinand Thief

Jocas Thief

Upvotes: 1

Views: 443

Answers (1)

MarcinJuraszek
MarcinJuraszek

Reputation: 125620

Use combination of Take and SelectMany:

var results = list.GroupBy(x => x.Category).SelectMany(g => g.Take(2)).ToList();

I've tested it on following Item class:

public class Item
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Category { get; set; }
}

And query:

List<Item> list = new List<Item>
{
    new Item { ID = 0, Name = "John", Category = "Police"}, 
    new Item { ID = 1, Name = "Michael", Category = "Police"},
    new Item { ID = 2, Name = "Alice", Category = "Police"}, 
    new Item { ID = 3, Name = "Ferdinand", Category = "Thief"}, 
    new Item { ID = 4, Name = "Jocas", Category = "Thief"}, 
    new Item { ID = 5, Name = "Connor", Category = "Thief"}
};

var results = list.GroupBy(x => x.Category).SelectMany(g => g.Take(2)).ToList();

Returns 4 elements, right as you want.

Upvotes: 5

Related Questions