Created
August 27, 2020 21:45
-
-
Save danielsimionescu/76814016be2f6708b1180b08c32bf99d to your computer and use it in GitHub Desktop.
C# Dictionaries - Sorting By Values and The ToDictionary() Method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
namespace SortingDictionary | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var store = new Dictionary<string, double> | |
{ | |
["peach"] = 15, | |
["grape"] = 23, | |
["lemon"] = 8, | |
["coconut"] = 10 | |
}; | |
string[] sortedStoreKeys = store | |
.Keys | |
.ToArray(); | |
Array.Sort(sortedStoreKeys); | |
foreach (var key in sortedStoreKeys) | |
{ | |
Console.WriteLine($"{key}: {store[key]}"); | |
} | |
Console.WriteLine(); | |
IEnumerable<string> storeKeysSortedByValue = store | |
.OrderBy(item => item.Value) | |
.Select(item => item.Key); | |
foreach (var key in storeKeysSortedByValue) | |
{ | |
Console.WriteLine($"{key}: {store[key]}"); | |
} | |
Console.WriteLine(); | |
Dictionary<string, double> sortedStoreByKey = store | |
.OrderBy(item => item.Key) | |
.ToDictionary(item => item.Key, item => item.Value); | |
foreach (var item in sortedStoreByKey) | |
{ | |
Console.WriteLine($"{item.Key}: {item.Value}"); | |
} | |
Console.WriteLine(); | |
Dictionary<string, double> sortedStoreByValue = store | |
.OrderBy(item => item.Value) | |
.ToDictionary(item => item.Key, item => item.Value); | |
foreach (var item in sortedStoreByValue) | |
{ | |
Console.WriteLine($"{item.Key}: {item.Value}"); | |
} | |
Console.ReadKey(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment