Ivan-Mark Debono
Ivan-Mark Debono

Reputation: 16290

How to group a list of objects into a dictionary?

I have list of:

public class Item
{
   public int FirstId { get; set; }
   public int SecondId { get; set; }
   public int Sequence { get; set; }
}

A sample list might be:

var list = new List<Item>();
list.Add( new Item{ FirstId = 1, SecondId = 10, Sequence = 1 } );
list.Add( new Item{ FirstId = 2, SecondId = 10, Sequence = 1 } );
list.Add( new Item{ FirstId = 2, SecondId = 11, Sequence = 2 } );
list.Add( new Item{ FirstId = 3, SecondId = 10, Sequence = 1 } );
list.Add( new Item{ FirstId = 4, SecondId = 10, Sequence = 2 } );
list.Add( new Item{ FirstId = 4, SecondId = 11, Sequence = 1 } );

I need to group the items by FirstId and sort each group by Sequence. The result should be:

Dictionary<int, IEnumerable<int>>();

where the key is FirstId, and value is the list of SecondId ordered by Sequence. So the result of the above should be:

Key (int), Value (IEnumerable<int>)
1, (10)
2, (10, 11)
3, (10)
4, (11, 10)

Currently I have the following:

var items = from t in tags
            group t by t.FirstId into g
            orderby g.Key
            select g;

How can I expand on the above to achieve what I need?

Upvotes: 0

Views: 100

Answers (1)

Aleks Andreev
Aleks Andreev

Reputation: 7054

You can use method ToDictionary. Try this code:

tags
  .GroupBy(t => t.FirstId)
  .ToDictionary(k => k.Key, g => g.OrderBy(t => t.Sequence).Select(t => t.SecondId));

Demo

Upvotes: 4

Related Questions