Guest User

Nested Dictionary with Sorted Values

a guest
Oct 11th, 2016
256
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace _07.Population_Center
  8. {
  9. class Program
  10. {
  11. static void Main(string[] args)
  12. {
  13.  
  14. string input = Console.ReadLine();
  15.  
  16. var countryWithTown = new Dictionary<string, Dictionary<string, int>>();
  17.  
  18. while (input != "report")
  19. {
  20. string[] inputInfo = input.Split('|');
  21. var country = inputInfo[1];
  22. var town = inputInfo[0];
  23. int population = int.Parse(inputInfo[2]);
  24. if (!countryWithTown.ContainsKey(country))
  25. {
  26. countryWithTown.Add(country, new Dictionary<string, int>());
  27. }
  28. countryWithTown[country].Add(town, population);
  29.  
  30. input = Console.ReadLine();
  31. }
  32.  
  33. var countryWithTotalPopulation = new Dictionary<string, int>();
  34.  
  35. foreach (var pair in countryWithTown)
  36. {
  37. var currentCountry = pair.Key;
  38. countryWithTotalPopulation.Add(currentCountry, 0);
  39. foreach (var pair2 in countryWithTown[currentCountry])
  40. {
  41. countryWithTotalPopulation[currentCountry] += pair2.Value;
  42. }
  43. }
  44.  
  45. //all total populations added
  46. //now we sort them
  47.  
  48. foreach (KeyValuePair<string, int> item in countryWithTotalPopulation.OrderByDescending(key => key.Value))
  49. {
  50. // do something with item.Key and item.Value
  51. Console.WriteLine("{0} (total population: {1})",item.Key,item.Value);
  52. foreach (var townPair in countryWithTown[item.Key].OrderByDescending(key => key.Value))
  53. {
  54. Console.WriteLine("=>{0}: {1}",townPair.Key,townPair.Value);
  55. }
  56. }
  57.  
  58. }
  59.  
  60. }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment