Reputation: 4171
Suppose we have a
var dictionary= new Dictionary<int, IList<int>>();
What I want is to ouput a sorted version of it, ordered first by keys and then by values inside a list.
E.g.
1 2, 1, 6
5 2, 1
2 1, 3
Becomes
1 1, 2, 6
2 1, 3
5 1, 2
I tried doing it inside foreach
, but obviously this is a bad idea to change the thing you are iterating.
Upvotes: 6
Views: 9502
Reputation: 2939
Try this:
// Creating test data
var dictionary = new Dictionary<int, IList<int>>
{
{ 1, new List<int> { 2, 1, 6 } },
{ 5, new List<int> { 2, 1 } },
{ 2, new List<int> { 2, 3 } }
};
// Ordering as requested
dictionary = dictionary
.OrderBy(d => d.Key)
.ToDictionary(
d => d.Key,
d => (IList<int>)d.Value.OrderBy(v => v).ToList()
);
// Displaying the results
foreach(var kv in dictionary)
{
Console.Write("\n{0}", kv.Key);
foreach (var li in kv.Value)
{
Console.Write("\t{0}", li);
}
}
Upvotes: 12
Reputation: 131433
You can use LINQ to order the contents of the dictionary like this:
var dictionary = new Dictionary<int, IList<int>>();
var orderedItems = dictionary
.OrderBy(pair => pair.Key)
.Select(new {
Key = pair.Key,
Value = pair.Value.OrderBy(i => i)});
Of course, this is rather ugly. A better option at this point is to use LINQ syntax
var orderedItems =from pair in dictionary
orderby pair.Key
let values = pair.Value.OrderBy(i => i)
select new { Key = pair.Key, Value = values };
If you need to use the resulting IEnumerable as a list or array, you can create one using ToList or ToArray. In most cases though, you can just use the IEnumerable as it is
Upvotes: 3
Reputation: 51634
A Dictionary
is unsorted. To sort a dictionary you can use the OrderedDictionary
.
To sort the lists, you can use List<T>.OrderBy()
Upvotes: 3
Reputation: 921
You can loop through the dictionary items and sort each list seperately. it will look like this:
SortDictionary(dictionary);
after that:
foreach (System.Collections.Generic.KeyValuePair<int,IList<int>> list in dictionary)
{
SortDictionary( list.Value)
}
Upvotes: 0