Advertisement
n4wn4w

C# Dictionary

Apr 15th, 2015
480
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 52.04 KB | None | 0 0
  1.  Dictionary<string,List<int>> grades = new Dictionary<string,List<int>>();
  2.             grades["Peshi"] = new List<int>() {5,5,6,7,8 };
  3.             grades["Gosho"] = new List<int>() {  5, 8 };
  4.             grades["Kondio"] = new List<int>() { 2, 2, 3, 74, 8 };
  5.             grades["Ivan"] = new List<int>() { 6, 6, 6, 6, 6 };
  6.             grades["SHOSHO"] = new List<int>() { 54, 57, 86,47, 58 };
  7.  
  8.            
  9.  
  10.             grades.Remove("Gosho");
  11.            
  12.  
  13.             if (grades.ContainsKey("Kondio"))
  14.             {
  15.                 Console.WriteLine("Kondio ima takiva ocenki :");
  16.                 foreach (var g in grades["Kondio"])
  17.                 {
  18.                     Console.Write(g + " ");
  19.                 }
  20.                 Console.WriteLine();
  21.             }
  22.             else
  23.             {
  24.                 Console.WriteLine("NQMA OCENKI");
  25.             }
  26.  
  27. //////////////////////////////////////////////////////////////////////
  28.  
  29. // Create an events table: a set of pairs of (date -> event)
  30.         Dictionary<DateTime, string> events = new Dictionary<DateTime, string>();
  31.  
  32.         // Put a few events
  33.         events[new DateTime(1998, 9, 4)] = "Google's birth date";
  34.         events[new DateTime(2013, 11, 5)] = "Software University's birth date";
  35.         events[new DateTime(1975, 4, 4)] = "Microsoft's birth date";
  36.         events[new DateTime(2004, 2, 4)] = "Facebook's birth date";
  37.         events[new DateTime(2013, 11, 5)] =
  38.             "Nakov left Telerik Academy to establish the Software University";
  39.  
  40.         Console.WriteLine("List of all events:");
  41.         foreach (var entry in events)
  42.         {
  43.             Console.WriteLine("{0:dd-MMM-yyyy}: {1}", entry.Key, entry.Value);
  44.         }
  45.  
  46.         Console.WriteLine();
  47.         Console.WriteLine("List of all dates:");
  48.         foreach (var date in events.Keys)
  49.         {
  50.             Console.WriteLine("{0:dd-MMM-yyyy}", date);
  51.         }
  52.  
  53.         Console.WriteLine();
  54.         Console.WriteLine("List of all event names:");
  55.         foreach (var name in events.Values)
  56.         {
  57.             Console.WriteLine("{0}", name);
  58.         }
  59.  
  60.  
  61. /////////////////////////////////////////////////////////////////////////////////
  62.  
  63. // Create a phone book: a set of pairs of (person name -> phone number)
  64.         Dictionary<string, string> phonebook = new Dictionary<string, string>()
  65.         {
  66.             {"Steve Ryan", "+1-555-1730"},
  67.             {"Alex Shillds", "+1-555-1256"},
  68.         };
  69.  
  70.         // Add a few entries in the phonebook
  71.         phonebook["John Smith"] = "+1-555-8976";
  72.         phonebook["Lisa Smith"] = "+1-555-1234";
  73.         phonebook["Sam Doe"] = "+1-555-5030";
  74.         phonebook["Nakov"] = "+359-899-555-592";
  75.  
  76.         // Print the phonebook
  77.         foreach (var entry in phonebook)
  78.         {
  79.             Console.WriteLine("{0} has phone number {1}", entry.Key, entry.Value);
  80.         }
  81.  
  82.         // Modify Nakov's number
  83.         phonebook["Nakov"] = "+359-2-981-9819";
  84.  
  85.         // Delete an existing number
  86.         phonebook.Remove("John Smith");
  87.  
  88.         Console.WriteLine();
  89.  
  90.         // Print the phonebook (another way)
  91.         foreach (var name in phonebook.Keys)
  92.         {
  93.             Console.WriteLine("{0} --> {1}", name, phonebook[name]);
  94.         }
  95.  
  96.  
  97. /////////////////////////////////////   counting words  DICTIONARY ////////////////////////
  98.  
  99.  static void Main()
  100.     {
  101.         string text = "Welcome to our C# course. In this " +
  102.             "course you will learn how to write simple " +
  103.             "programs in C# and how to use data structures";
  104.  
  105.         Console.WriteLine("Dictionary<TKey,TValue>");
  106.         Console.WriteLine("-----------------------");
  107.         IDictionary<string, int> wordsCount = new Dictionary<string, int>();
  108.         CountWords(text, wordsCount);
  109.  
  110.         Console.WriteLine();
  111.         Console.WriteLine("SortedDictionary<TKey,TValue>");
  112.         Console.WriteLine("-----------------------------");
  113.         IDictionary<string, int> sortedWordsCount =
  114.             new SortedDictionary<string, int>();
  115.         CountWords(text, sortedWordsCount);
  116.     }
  117.  
  118.     private static void CountWords(string text, IDictionary<string, int> wordsCount)
  119.     {
  120.         string[] words = text.Split(new char[] { ' ', ',', '.' },
  121.             StringSplitOptions.RemoveEmptyEntries);
  122.         foreach (string word in words)
  123.         {
  124.             int count = 1;
  125.             if (wordsCount.ContainsKey(word))
  126.             {
  127.                 count = wordsCount[word] + 1;
  128.             }
  129.             wordsCount[word] = count;
  130.         }
  131.         foreach (var pair in wordsCount)
  132.         {
  133.             Console.WriteLine("{0} --> {1}", pair.Key, pair.Value);
  134.         }
  135.     }
  136. }
  137.  
  138. ////////////////////////////////////////////   ///////////////////////////////////////////////////////////////////      
  139.  
  140.  Dictionary<string, int> studentsMarks =
  141.         new Dictionary<string, int>();
  142.         studentsMarks.Add("Ivan", 4);
  143.         studentsMarks.Add("Peter", 6);
  144.         studentsMarks.Add("Maria", 6);
  145.         studentsMarks.Add("George", 5);
  146.  
  147.         int peterMark = studentsMarks["Peter"];
  148.         Console.WriteLine("Peter's mark: {0}", peterMark);
  149.  
  150.         Console.WriteLine("Is Peter in the hash table: {0}",
  151.             studentsMarks.ContainsKey("Peter"));
  152.  
  153.         studentsMarks.Remove("Peter");
  154.         Console.WriteLine("Peter removed.");
  155.  
  156.         Console.WriteLine("Is Peter in the hash table: {0}",
  157.             studentsMarks.ContainsKey("Peter"));
  158.  
  159.         Console.WriteLine("Ivan's mark: {0}", studentsMarks["Ivan"]);
  160.  
  161.         studentsMarks["Ivan"] = 3;
  162.         Console.WriteLine("Ivan's mark changed.");
  163.  
  164.         // Print all elements of the hash table
  165.         Console.WriteLine("Students and grades:");
  166.         foreach (var studentMark in studentsMarks)
  167.         {
  168.             Console.WriteLine("{0} --> {1}",
  169.                 studentMark.Key, studentMark.Value);
  170.         }
  171.  
  172.  
  173.  
  174. ////////////////////////////////////////////////////////////////////////
  175.  
  176.  
  177. static Dictionary<string, List<int>> studentGrades =
  178.         new Dictionary<string, List<int>>();
  179.  
  180.     private static void AddGrade(string name, int grade)
  181.     {
  182.         if (! studentGrades.ContainsKey(name))
  183.         {
  184.             studentGrades[name] = new List<int>();
  185.         }
  186.         studentGrades[name].Add(grade);
  187.     }
  188.  
  189.     private static void PrintAllGrades()
  190.     {
  191.         foreach (var studentAndGrade in studentGrades)
  192.         {
  193.             Console.WriteLine(studentAndGrade.Key + ": ");
  194.             foreach (var grade in studentAndGrade.Value)
  195.             {
  196.                 Console.WriteLine("\t" + grade);
  197.             }
  198.         }
  199.     }
  200.  
  201.     static void Main()
  202.     {
  203.         AddGrade("Nakov", 6);
  204.         AddGrade("Nakov", 5);
  205.         AddGrade("Maria", 3);
  206.         AddGrade("Maria", 4);
  207.         AddGrade("Nakov", 6);
  208.         AddGrade("Maria", 3);
  209.         AddGrade("Kiril", 4);
  210.  
  211.         PrintAllGrades();
  212.     }
  213.  
  214.  
  215.  
  216. ///////////////////////////////////////////   izkarvane list o ocenki po4ti sushstoto kato goranata zadacha /////////////////
  217.  
  218.  
  219. static SortedDictionary<string, List<int>> grades = new SortedDictionary<string, List<int>>();
  220.              static void Main()
  221.     {
  222.  
  223.         grades["Peshi"] = new List<int>() { 5, 5, 6, 7, 8 };
  224.         grades["Gosho"] = new List<int>() { 5, 8 };
  225.         grades["Kondio"] = new List<int>() { 2, 2, 3, 74, 8 };
  226.         grades["Ivan"] = new List<int>() { 6, 6, 6, 6, 6 };
  227.         grades["SHOSHO"] = new List<int>() { 54, 57, 86, 47, 58 };
  228.  
  229.  
  230.         foreach (KeyValuePair<string, List<int>> stud in grades)
  231.         {
  232.  
  233.             Console.Write(stud.Key + " : ");
  234.             foreach (var mark in stud.Value)
  235.             {
  236.                 Console.Write(mark + " ");
  237.             }
  238.             Console.WriteLine();
  239.         }
  240.       }
  241.  
  242.                  static void addmark ( string studentName , int mark  )
  243.                  {
  244.  
  245.                      List<int> studMarks;
  246.                      if (grades.ContainsKey(studentName))
  247.                      {
  248.                          studMarks = grades[studentName];
  249.                      }
  250.                      else
  251.                      {
  252.                          studMarks = new List<int>();
  253.                          grades[studentName] = studMarks;
  254.                      }
  255.                      studMarks.Add(mark);
  256.                  }
  257.  
  258. ///////////////////////// broene na dumi 2 reshenie napisano s natrupvane na dumi po dr nachin i sortirane po VALUE /////
  259.  
  260.  string text = "Welcome to our C# course. In this " +
  261.             "course you will learn how to write simple " +
  262.             "programs in C# and how to use data structures";
  263.  
  264.         Console.WriteLine("Dictionary<TKey,TValue>");
  265.         Console.WriteLine("-----------------------");
  266.         IDictionary<string, int> wordsCount = new Dictionary<string, int>();
  267.         CountWords(text, wordsCount);
  268.  
  269.         Console.WriteLine();
  270.         Console.WriteLine("SortedDictionary<TKey,TValue>");
  271.         Console.WriteLine("-----------------------------");
  272.         IDictionary<string, int> sortedWordsCount =
  273.             new SortedDictionary<string, int>();
  274.         CountWords(text, sortedWordsCount);
  275.     }
  276.  
  277.     private static void CountWords(string text, IDictionary<string, int> wordsCount)
  278.     {
  279.         string[] words = text.Split(new char[] { ' ', ',', '.' },
  280.             StringSplitOptions.RemoveEmptyEntries);
  281.         foreach (string word in words)
  282.         {
  283.             if (!wordsCount.ContainsKey(word))
  284.             {
  285.                 wordsCount.Add(word, 1);
  286.             }
  287.             else
  288.             {
  289.                 wordsCount[word]++;
  290.             }
  291.  
  292.         }
  293.        
  294.         wordsCount = wordsCount.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value);
  295.        
  296.         foreach (var pair in wordsCount)
  297.         {
  298.             Console.WriteLine("{0} --> {1}", pair.Key, pair.Value);
  299.         }
  300.  
  301.  
  302.  
  303. /////////////////////////////// za stavnqvane na to4ki //////////////////////////////////////////////
  304.  
  305.  
  306.  List<Point> points = new List<Point>();
  307.  
  308.  
  309.             points.Add(new Point { X = 5, Y = 106 });
  310.             points.Add(new Point { X = 54, Y = 105 });
  311.             points.Add(new Point { X = 55, Y = 104 });
  312.             points.Add(new Point { X = 56, Y = 10 });
  313.             points.Add(new Point { X = 58, Y = 103 });
  314.             points.Add(new Point { X = 45, Y = 103 });
  315.             points.Add(new Point { X = 35, Y = 10 });
  316.             points.Add(new Point { X = 85, Y = 102 });
  317.             points.Add(new Point { X = 95, Y = 10 });
  318.  
  319.  
  320.             points.Sort();
  321.  
  322.             foreach (var item in points)
  323.             {
  324.                 Console.WriteLine( item.X + " - " +  item.Y);
  325.             }
  326.  
  327.         }
  328.      
  329.          //////////////////////////////////
  330.        
  331.             public struct Point : IComparable<Point>
  332.             {
  333.                 public int X { get; set; }
  334.                 public int Y { get; set; }
  335.  
  336.                 public int CompareTo(Point otherPoint)
  337.                 {
  338.                     if (X != otherPoint.X)
  339.                     {
  340.                         return this.X.CompareTo(otherPoint.X);
  341.                     }
  342.                     else
  343.                     {
  344.                          return this.Y.CompareTo(otherPoint.Y);
  345.                     }
  346.                 }
  347.             }
  348.  
  349.  
  350.  
  351. ///////////////////// java basic exam zadachi ///////////////////////////////////////////////////////
  352.  
  353.  
  354. //////  3 septemvri za  msecite begachite i raztoqnieto ///////////////////////////////////////////////////
  355.  
  356. using System;
  357. using System.Collections.Generic;
  358.  
  359. class ActivityTracker
  360. {
  361.     static void Main()
  362.     {
  363.         SortedDictionary<int, SortedDictionary<string, int>> dataDictionary =
  364.                                             new SortedDictionary<int, SortedDictionary<string, int>>();
  365.  
  366.         int dataLinesNumber = int.Parse(Console.ReadLine());
  367.         string lineContents = String.Empty;
  368.         string[] lineTokens;
  369.         int month = 0;
  370.         string user = String.Empty;
  371.         int distance = 0;
  372.         for (int i = 0; i < dataLinesNumber; i++)
  373.         {
  374.             lineContents = Console.ReadLine();
  375.             lineTokens = lineContents.Split(new char[] { ' ', '/' }, StringSplitOptions.RemoveEmptyEntries);
  376.             month = int.Parse(lineTokens[1]);
  377.             user = lineTokens[3];
  378.             distance = int.Parse(lineTokens[4]);
  379.  
  380.             if (!dataDictionary.ContainsKey(month))
  381.             {
  382.                 dataDictionary[month] = new SortedDictionary<string, int>();
  383.             }
  384.  
  385.             if (!dataDictionary[month].ContainsKey(user))
  386.             {
  387.                 dataDictionary[month][user] = distance;
  388.             }
  389.             else
  390.             {
  391.                 dataDictionary[month][user] += distance;
  392.             }
  393.         }
  394.  
  395.         bool isFirstPair = true;
  396.         foreach (var dataPair in dataDictionary)
  397.         {
  398.             Console.Write("{0}: ", dataPair.Key);
  399.             isFirstPair = true;
  400.             foreach (var subPair in dataPair.Value)
  401.             {
  402.                 if (isFirstPair)
  403.                 {
  404.                     Console.Write("{0}({1})", subPair.Key, subPair.Value);
  405.                     isFirstPair = false;
  406.                 }
  407.                 else
  408.                 {
  409.                     Console.Write(", {0}({1})", subPair.Key, subPair.Value);
  410.                 }
  411.             }
  412.             Console.WriteLine();
  413.         }
  414.     }
  415. }
  416.  
  417.  
  418.  
  419.  
  420.  
  421. 26  may 2014  //////////////////////////////////////////////////////////////////////
  422. ///// dvoiki 4isla 3 4, 4 2 , 2 3, kolko puti se povtarqt i da izkarva i procentite
  423.  
  424.  
  425.   string allLangs = @"3 4 2 3 4 2 1 12 2 3 4".ToUpper();
  426.  
  427.             string[] langs = allLangs.Split(new char[] { ',', ';', ' ', '.', '!', '\'', '"', '$', '?', '+', '"', '\n', '\r' },
  428.                 StringSplitOptions.RemoveEmptyEntries);
  429.  
  430.             List<string> lettersCouples = new List<string>();
  431.             string kor = langs[0];
  432.             for (int i = 1; i < langs.Length; i++)
  433.             {
  434.  
  435.                 string DigitCouple = kor + " " +langs[i];
  436.                
  437.                 lettersCouples.Add(DigitCouple);
  438.                 kor = langs[i];
  439.  
  440.             }
  441.  
  442.             Dictionary<string, int> dict = new Dictionary<string, int>();
  443.             double countLetter = 0;
  444.  
  445.             foreach (var t in lettersCouples)
  446.             {
  447.                 if (!dict.ContainsKey(t))
  448.                 {
  449.                     dict.Add(t, 1);
  450.                     countLetter++;
  451.                 }
  452.                 else
  453.                 {
  454.                     dict[t]++;
  455.                     countLetter++;
  456.  
  457.                 }
  458.             }
  459.  
  460.  
  461.             List<KeyValuePair<string, int>> myList = dict.ToList();
  462.  
  463.             myList.Sort(
  464.                 delegate(KeyValuePair<string, int> firstPair,
  465.                 KeyValuePair<string, int> nextPair)
  466.                 {
  467.                     return firstPair.Value.CompareTo(nextPair.Value);
  468.                 }
  469.             );
  470.  
  471.             myList.Reverse();
  472.            
  473.  
  474.  
  475.             foreach (var dr in myList)
  476.             {
  477.                 double Procent = (dr.Value / countLetter) * 100;
  478.  
  479.  
  480.                 Console.WriteLine("{0,4} = {1,3} -> {2,1}>% {3:0.00}", dr.Key, dr.Value, new string('#', dr.Value), Procent);
  481.             }
  482.  
  483.  
  484. /////////////////////// 27 may 4 zadacha ORDERS /////////////////////////////////////////////////////////////////
  485.  
  486.  
  487.   SortedDictionary<string, SortedDictionary<string, int>> dataDictionary =
  488.                                             new SortedDictionary<string, SortedDictionary<string, int>>();
  489.  
  490.             int dataLinesNumber = int.Parse(Console.ReadLine());
  491.             string lineContents = String.Empty;
  492.             string[] lineTokens;
  493.             string fruit = "";
  494.             string user = String.Empty;
  495.             int kolichestvo = 0;
  496.             for (int i = 0; i < dataLinesNumber; i++)
  497.             {
  498.                 lineContents = Console.ReadLine();
  499.                 lineTokens = lineContents.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
  500.                 fruit = (lineTokens[2]);
  501.                 user = lineTokens[0];
  502.                 kolichestvo = int.Parse(lineTokens[1]);
  503.  
  504.                 if (!dataDictionary.ContainsKey(fruit))
  505.                 {
  506.                     dataDictionary[fruit] = new SortedDictionary<string, int>();
  507.                 }
  508.  
  509.                 if (!dataDictionary[fruit].ContainsKey(user))
  510.                 {
  511.                     dataDictionary[fruit][user] = kolichestvo;
  512.                 }
  513.                 else
  514.                 {
  515.                     dataDictionary[fruit][user] += kolichestvo;
  516.                 }
  517.             }
  518.  
  519.             bool isFirstPair = true;
  520.             foreach (var dataPair in dataDictionary)
  521.             {
  522.                 Console.Write("{0}: ", dataPair.Key);
  523.                 isFirstPair = true;
  524.                 foreach (var subPair in dataPair.Value)
  525.                 {
  526.                     if (isFirstPair)
  527.                     {
  528.                         Console.Write("{0}({1})", subPair.Key, subPair.Value);
  529.                         isFirstPair = false;
  530.                     }
  531.                     else
  532.                     {
  533.                         Console.Write(", {0}({1})", subPair.Key, subPair.Value);
  534.                     }
  535.                 }
  536.                 Console.WriteLine();
  537.  
  538.  
  539.  
  540.  
  541. /////// 1 uni  192.168.0.11 peter 33 10.10.17.33 alex 12 10.10.17.35 peter 30 /////////////////////////////////
  542. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  543.  
  544.  
  545. using System;
  546. using System.Collections.Generic;
  547. using System.Linq;
  548. using System.Text;
  549.  
  550. namespace ConsoleApplication4
  551. {
  552.     class Program
  553.     {
  554.         static void Main(string[] args)
  555.         {
  556.             SortedDictionary<string, int> dataDictionary =
  557.                                                      new SortedDictionary<string, int>();
  558.  
  559.             SortedDictionary<string, SortedSet<string>> dataIp =
  560.                                                       new SortedDictionary<string, SortedSet<string>>();
  561.  
  562.  
  563.             int dataLinesNumber = int.Parse(Console.ReadLine());
  564.             string lineContents = String.Empty;
  565.             string[] lineTokens;
  566.             string ip = "";
  567.             string user = String.Empty;
  568.             int kolichestvo = 0;
  569.             int count = 0;
  570.             for (int i = 0; i < dataLinesNumber; i++)
  571.             {
  572.                 lineContents = Console.ReadLine();
  573.                 lineTokens = lineContents.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
  574.                 ip = (lineTokens[0]);
  575.                 user = lineTokens[1];
  576.                 kolichestvo = int.Parse(lineTokens[2]);
  577.  
  578.                 if (!dataDictionary.ContainsKey(user))
  579.                 {
  580.                     dataDictionary[user] = kolichestvo;
  581.                     count++;
  582.                 }
  583.                 else
  584.                 {
  585.                     dataDictionary[user] += kolichestvo;
  586.                 }
  587.                 //////////////// 2 dictonary
  588.                 if (!dataIp.ContainsKey(user))
  589.                 {
  590.                     dataIp[user] = new SortedSet<string>();
  591.                     dataIp[user].Add(ip);
  592.                 }
  593.                 else
  594.                 {
  595.                     dataIp[user].Add(ip);
  596.                 }
  597.             }
  598.  
  599.        
  600.             int kondio = 0;
  601.  
  602.             bool kur = true;
  603.             ///////////////  output
  604.             foreach (var dataPair in dataDictionary)
  605.             {
  606.                 kur = true;
  607.                 foreach (var item in dataIp)
  608.                 {
  609.                     kondio++;
  610.                     if (kondio == 1 || kondio == 4)
  611.                     {
  612.                         Console.Write(item.Key + ": ");
  613.                         Console.Write(dataPair.Value + " ");
  614.                         Console.Write("[");
  615.                         foreach (var ink in item.Value)
  616.                         {
  617.                        
  618.                             if (kur)
  619.                             {
  620.                                 Console.Write(ink);
  621.                                 kur = false;
  622.                             }
  623.                             else
  624.                             {
  625.                                 Console.Write(", " + ink);
  626.                             }
  627.  
  628.                         }
  629.                         Console.Write("]");
  630.                         Console.WriteLine();
  631.                     }
  632.                 }
  633.             }
  634.  
  635.         }
  636.     }
  637. }
  638.  
  639. 2 reshenie //////////////////////////////////////////////////////////////////////////////////////////////////////
  640.  
  641. using System;
  642. using System.Collections.Generic;
  643. using System.Linq;
  644.  
  645. class LogsAggregator
  646. {
  647.     static void Main()
  648.     {
  649.         int n = int.Parse(Console.ReadLine());
  650.  
  651.         SortedDictionary<string, SortedDictionary<string, int>> dataDic =
  652.                             new SortedDictionary<string, SortedDictionary<string, int>>();
  653.  
  654.         string input = string.Empty;
  655.         string[] inputTokens;
  656.         string name = string.Empty;
  657.         string ip = string.Empty;
  658.         int number;
  659.  
  660.         for (int i = 0; i < n; i++)
  661.         {
  662.             input = Console.ReadLine();
  663.             inputTokens = input.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
  664.             name = inputTokens[1];
  665.             ip = inputTokens[0];
  666.             number = int.Parse(inputTokens[2]);
  667.  
  668.             if (!dataDic.ContainsKey(name))
  669.             {
  670.                 dataDic[name] = new SortedDictionary<string, int>();
  671.             }
  672.             if (!dataDic[name].ContainsKey(ip))
  673.             {
  674.                 dataDic[name][ip] = number;
  675.             }
  676.             else
  677.             {
  678.                 dataDic[name][ip] += number;
  679.             }
  680.  
  681.         }
  682.  
  683.  
  684.         //output
  685.  
  686.  
  687.         foreach (var entry in dataDic)
  688.         {
  689.             string ips = String.Empty;
  690.             int finalDuration = 0;
  691.  
  692.             foreach (var innnerEntry in entry.Value)
  693.             {
  694.                 ips += innnerEntry.Key;
  695.                 ips += " ";
  696.                 finalDuration += innnerEntry.Value;
  697.             }
  698.  
  699.             Console.WriteLine(entry.Key + ": " + finalDuration + " [" + ips.Trim().Replace(" ", ", ") + "]");
  700.         }
  701.  
  702.  
  703.     }
  704. }
  705.  
  706.  
  707.  
  708.    
  709.  
  710.  
  711. tui   ////////////////////////////////////////////////////////////////////////////////////////
  712.  
  713.  SortedDictionary<string, List<int>> dataDictionary =
  714.                                                      new SortedDictionary<string, List<int>>();
  715.  
  716.             SortedDictionary<string, List<string>> dataIp =
  717.                                                       new SortedDictionary<string, List<string>>();
  718.  
  719.  
  720.             int dataLinesNumber = int.Parse(Console.ReadLine());
  721.             string lineContents = String.Empty;
  722.             string[] lineTokens;
  723.             string names = "";
  724.             string score = String.Empty;
  725.             int sredno = 0;
  726.             int count = 0;
  727.             for (int i = 0; i < dataLinesNumber; i++)
  728.             {
  729.                 lineContents = Console.ReadLine();
  730.                 lineTokens = lineContents.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
  731.                 names = (lineTokens[0]);
  732.                 score = lineTokens[1];
  733.                 sredno = int.Parse(lineTokens[2]);
  734.  
  735.                 if (!dataDictionary.ContainsKey(score))
  736.                 {
  737.                     dataDictionary[score] = new List<int>();
  738.                     dataDictionary[score].Add(sredno);
  739.                     count++;
  740.                 }
  741.                 else
  742.                 {
  743.                     dataDictionary[score].Add(sredno);
  744.                 }
  745.                 //////////////// 2 dictonary
  746.                 if (!dataIp.ContainsKey(score))
  747.                 {
  748.                     dataIp[score] = new List<string>();
  749.                     dataIp[score].Add(names);
  750.                 }
  751.                 else
  752.                 {
  753.                     dataIp[score].Add(names);
  754.                 }
  755.             }
  756.  
  757.        
  758.             int kondio = 0;
  759.  
  760.             bool kur = true;
  761.             ///////////////  output
  762.             foreach (var dataPair in dataDictionary)
  763.             {
  764.                 kur = true;
  765.                 foreach (var item in dataIp)
  766.                 {
  767.                     kondio++;
  768.                     if (kondio == 1 || kondio == 4)
  769.                     {
  770.                         Console.Write(item.Key + ": ");
  771.                         Console.Write(dataPair.Value + " ");
  772.                         Console.Write("[");
  773.                         foreach (var ink in item.Value)
  774.                         {
  775.                        
  776.                             if (kur)
  777.                             {
  778.                                 Console.Write(ink);
  779.                                 kur = false;
  780.                             }
  781.                             else
  782.                             {
  783.                                 Console.Write(", " + ink);
  784.                             }
  785.  
  786.                         }
  787.                         Console.Write("]");
  788.                         Console.WriteLine();
  789.                     }
  790.                 }
  791.             }
  792.  
  793.  
  794.  
  795.  
  796. //////////////////////////////  8 february 2015  ///////////////////////////////////////////////////////
  797.  
  798.  
  799. using System;
  800. using System.Collections.Generic;
  801. class NightLife
  802. {
  803.     static void Main()
  804.     {
  805.         SortedDictionary<string, SortedDictionary<string, int>> nightLifeDictionary =
  806.                             new SortedDictionary<string, SortedDictionary<string, int>>();
  807.  
  808.         string[] eventTokens;
  809.         string user = String.Empty;
  810.         string ip = String.Empty;
  811.         int broi = 0;
  812.         string eventInformation = Console.ReadLine();
  813.         int count = 0;
  814.         while (eventInformation != "END")
  815.         {
  816.             eventTokens = eventInformation.Split(new char[] { '=', ' ' }, StringSplitOptions.RemoveEmptyEntries);
  817.  
  818.             user = eventTokens[5];
  819.             ip = eventTokens[1];
  820.             if (!nightLifeDictionary.ContainsKey(user))
  821.             {
  822.                 nightLifeDictionary[user] = new SortedDictionary<string, int>();
  823.             }
  824.             if (!nightLifeDictionary[user].ContainsKey(ip))
  825.             {
  826.                 count = 0;
  827.                 count = 1;
  828.                 nightLifeDictionary[user][ip] = count;
  829.             }
  830.             nightLifeDictionary[user][ip] = count++;
  831.  
  832.             eventInformation = Console.ReadLine();
  833.         }
  834.  
  835.         foreach (var cityPair in nightLifeDictionary)
  836.         {
  837.             Console.WriteLine(cityPair.Key);
  838.             foreach (var venuePair in cityPair.Value)
  839.             {
  840.                 Console.WriteLine("->{0}: = {1}", venuePair.Key, String.Join(", ", venuePair.Value));
  841.             }
  842.         }
  843.     }
  844. }
  845.  
  846.  
  847.  
  848. //////////////////// 7 qnuari  / Student systemi u4enici  predmeti i srednite ocenki /////////////////////////////////
  849.  
  850.  
  851. using System;
  852. using System.Collections.Generic;
  853. class NightLife
  854. {
  855.     static void Main()
  856.     {
  857.         Dictionary<string, SortedDictionary<string, List<int>>> nightLifeDictionary =
  858.                             new Dictionary<string, SortedDictionary<string, List<int>>>();
  859.  
  860.         int dataLinesNumber = int.Parse(Console.ReadLine());
  861.         string lineContents = String.Empty;
  862.  
  863.         string[] eventTokens;
  864.         string student = String.Empty;
  865.         string predmet = String.Empty;
  866.         int ocenka = 0;
  867.         //  string eventInformation = Console.ReadLine();
  868.  
  869.         for (int i = 0; i < dataLinesNumber; i++)
  870.         {
  871.  
  872.             lineContents = Console.ReadLine();
  873.             eventTokens = lineContents.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
  874.  
  875.             student = (eventTokens[0]) + " " + (eventTokens[1]);
  876.             predmet = eventTokens[2];
  877.             ocenka = int.Parse(eventTokens[3]);
  878.  
  879.             if (!nightLifeDictionary.ContainsKey(student))
  880.             {
  881.                 nightLifeDictionary[student] = new SortedDictionary<string, List<int>>();
  882.             }
  883.             if (!nightLifeDictionary[student].ContainsKey(predmet))
  884.             {
  885.                 nightLifeDictionary[student][predmet] = new List<int>();
  886.             }
  887.             nightLifeDictionary[student][predmet].Add(ocenka);
  888.  
  889.  
  890.         }
  891.  
  892.         /////////////// out put
  893.         string kondio = "";
  894.         double sum = 0;
  895.         double count = 0;
  896.         double avg = 0;
  897.         bool isFirst = true;
  898.         foreach (var cityPair in nightLifeDictionary)
  899.         {
  900.             isFirst = true;
  901.             Console.Write(cityPair.Key + ": ");
  902.             Console.Write("[");
  903.             foreach (var venuePair in cityPair.Value)
  904.             {
  905.              
  906.                 if (isFirst)
  907.                 {
  908.                     Console.Write("{0}", venuePair.Key);
  909.                     isFirst = false;
  910.                 }
  911.                 else
  912.                 {
  913.                     Console.Write(", {0}", venuePair.Key);
  914.                 }
  915.                
  916.                 count = 0;
  917.                 sum = 0;
  918.                 foreach (var item in venuePair.Value)
  919.                 {
  920.                     count++;
  921.                     sum += item;
  922.                 }
  923.                 avg = sum / count;
  924.                 if (isFirst)
  925.                 {
  926.                     Console.Write(" - {0:F2}", avg);
  927.                     isFirst = false;
  928.                 }
  929.                 else
  930.                 {
  931.                     Console.Write(" - {0:F2}", avg);
  932.                 }
  933.             }
  934.             Console.Write("]");
  935.             Console.WriteLine();
  936.         }
  937.     }
  938. }
  939.  
  940.  2 reshenie  ////////////////////////////////////////////////////////////////////////////////////////////////
  941.  
  942.  
  943. using System;
  944. using System.Collections.Generic;
  945. using System.Linq;
  946. using System.Text;
  947. using System.Threading.Tasks;
  948.  
  949. namespace ConsoleApplication28
  950. {
  951.     internal class Program // Nasko Lapchev
  952.     {
  953.         private static void Main(string[] args)
  954.         {
  955.             // databases
  956.             SortedDictionary<string,
  957.             SortedDictionary<string, List<double>>> dataDictionary =
  958.                 new SortedDictionary<string, SortedDictionary<string, List<double>>>(); // тук събираме студенти, предмети, оценки
  959.  
  960.             // тук слагаме накрая форматираните за печат резултати от събраната информация
  961.             SortedDictionary<string, SortedSet<string>> finals = new SortedDictionary<string, SortedSet<string>>();
  962.  
  963.             //SortedDictionary<string, SortedDictionary<string, double>> dataO =
  964.             //new SortedDictionary<string, SortedDictionary<string, double>>();
  965.  
  966.             // input
  967.             int dataLinesNumber = int.Parse(Console.ReadLine());
  968.  
  969.             // declarations - страхотна идея - дава яснота на кода по-нататък
  970.             string lineContents = String.Empty;
  971.             string[] lineTokens;
  972.             string student = "";
  973.             string predmet = String.Empty;
  974.             int ocenka = 0;
  975.  
  976.             // reading and parsing the lines
  977.             // имаме 3 основни случая:
  978.             // 1. такъв студент още не е добавян:
  979.             // * правим List<double> за оценките му, и прибавяме оценката към този лист
  980.             // * правим SortedDictionary<string, List<double>> studentData, и към него прибавяме предмета, и списъка с оценки (списък за да можем да прибавим и следващи оценки ако се появят
  981.             // * чак сега вече можем да прибавим към  dataDictionary.Add(student, studentData);
  982.             // 2. Вече има такъв студент додразбира се че и SortedDictionary<string, List<double>> studentData вече има, тъй като този речник се прибавя заедно със студента),
  983.             // но предмета е нов: правим List<double> ocenki = new List<double>();, и прибавяме dataDictionary[student].Add(predmet, ocenki);
  984.             // 3. има такъв студент, има такъв предмет, само оценката е нова
  985.             // тогава: dataDictionary[student][predmet].Add(ocenka);
  986.  
  987.             for (int i = 0; i < dataLinesNumber; i++)
  988.             {
  989.                 lineContents = Console.ReadLine();
  990.                 lineTokens = lineContents.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
  991.                 student = (lineTokens[0]) + " " + (lineTokens[1]);
  992.  
  993.                 predmet = lineTokens[2];
  994.                 ocenka = int.Parse(lineTokens[3]);
  995.  
  996.                 if (!dataDictionary.ContainsKey(student))
  997.                 {
  998.                     // ако в речника още няма такъв студент - няма как да прибавяме към него, трябва първо да го създадем
  999.                     // същото с информацията за студента (SortedDictionary<string, List<double>> studentData) -
  1000.                     // използвах твоята идея за речника предмет-оценка, но го развих в предмет-оценки: за да може в един List<double> с оценки да пълним всички оценки
  1001.                     // между другото - за разлика от теб щях да се сетя че трябва оценките да са double - не по рано от 1 час селд като съм почнала да пиша кода :)
  1002.                     SortedDictionary<string, List<double>> studentData = new SortedDictionary<string, List<double>>();
  1003.                     List<double> ocenki = new List<double>(); // ако искаш може да смениш "ocenka/i" с grade/s
  1004.  
  1005.                     ocenki.Add(ocenka);
  1006.                     studentData.Add(predmet, ocenki);
  1007.                     dataDictionary.Add(student, studentData); // чак сега вече можем да добавим нов студент в речника
  1008.                 }
  1009.  
  1010.                 else if (dataDictionary.ContainsKey(student))
  1011.                 {
  1012.                     if (!dataDictionary[student].ContainsKey(predmet))
  1013.                     {
  1014.                         //dataDictionary[student][predmet] = new List<double>(); // мисля че няма да можем да прибавим оценки ако няма такъв студент и ние още не сме го добавили
  1015.                         // иначе казано, за да го има студента вече в речника, тяй е бил добавен заедно с SortedDictionary<string, List<double>> studentData, и там вече си има друг предмет, с други оценки
  1016.                         // остава само да добавим във вътрешня речник studentDatа нов предмет, с оценките към него
  1017.                         List<double> ocenki = new List<double>();
  1018.                         ocenki.Add(ocenka);
  1019.                         dataDictionary[student].Add(predmet, ocenki);
  1020.                     }
  1021.                     else if (dataDictionary[student].ContainsKey(predmet))
  1022.                     {
  1023.                         // за да го има предмета, той е бил добавен с List<double> с оценки, сега остава само да прибавим още една оценка
  1024.                         dataDictionary[student][predmet].Add(ocenka);
  1025.                     }
  1026.                 }
  1027.             }
  1028.  
  1029.             // сега идеяата е точно както ти попита: да се подготвим за печатане, ще превърнем всичката информация за студента в един форматиран стринг
  1030.             foreach (var pair in dataDictionary)
  1031.             {
  1032.                 SortedSet<string> infoPoPredmeti = new SortedSet<string>();
  1033.                 foreach (var pair2 in pair.Value) // трябва ни само информацияята за студента, без самия студент
  1034.                 {
  1035.                     string predmet_srednaocenka = String.Format("{0} - {1:F2}", pair2.Key, pair2.Value.Average()); // така форматираме с колко знака след десетичната точка ще се печата средната оценка
  1036.                     //  и за всеки предмет ще получим нещо такова: "history – 5.00"
  1037.  
  1038.                     infoPoPredmeti.Add(predmet_srednaocenka); // тук са събрани всички стрингове от типа "history – 5.00", за един студент само
  1039.                 }
  1040.                 finals.Add(pair.Key, infoPoPredmeti); // тук прибавяме студента, със съответната infoPoPredmeti
  1041.             }
  1042.  
  1043.             foreach (var pair in finals)
  1044.             {
  1045.                 string infoZaStudenta = string.Join(", ", pair.Value);
  1046.                 Console.WriteLine("{0}: [{1}]", pair.Key, infoZaStudenta);
  1047.             }
  1048.         }
  1049.     }
  1050. }
  1051.  
  1052. 3 reshenie ///////////////////////////////////////////////////////////////////////////////////////////
  1053.  
  1054.  
  1055. using System;
  1056. using System.Collections.Generic;
  1057. using System.Linq;
  1058. using System.Text;
  1059. using System.Threading.Tasks;
  1060.  
  1061. namespace SchoolSystem
  1062. {
  1063.     class Program
  1064.     {
  1065.         static void Main()
  1066.         {
  1067.             var count = int.Parse(Console.ReadLine());
  1068.             var students = new SortedDictionary<string, SortedDictionary<string, List<double>>>();
  1069.             for (int i = 0; i < count; i++)
  1070.             {
  1071.                 var inputRow = Console.ReadLine();
  1072.                 var student = inputRow.Split(' ');
  1073.                 var fullName = student[0] + " " + student[1];
  1074.                 var subject = student[2];
  1075.                 var score = double.Parse(student[3]);
  1076.                 if (students.ContainsKey(fullName))
  1077.                 {
  1078.                     if (students[fullName].ContainsKey(subject))
  1079.                     {
  1080.                         students[fullName][subject].Add(score);
  1081.                     }
  1082.                     else
  1083.                     {
  1084.                         var scores = new List<double>();
  1085.                         scores.Add(score);
  1086.                         students[fullName].Add(subject, scores);
  1087.                     }
  1088.                 }
  1089.                 else
  1090.                 {
  1091.                     var scores = new List<double>();
  1092.                         scores.Add(score);
  1093.                         var subjects = new SortedDictionary<string, List<double>>();
  1094.                         subjects.Add(subject, scores);
  1095.                     students.Add(fullName, subjects);
  1096.                 }
  1097.             }
  1098.             foreach (var student in students)
  1099.             {
  1100.                 var sub = student.Value.Select(x=> x.Key + " - " + x.Value.Average().ToString("0.00")).Aggregate((x, y)=> x + ", " + y);
  1101.                 Console.WriteLine("{0}: [{1}]", student.Key, sub);
  1102.             }
  1103.         }
  1104.     }
  1105. }
  1106.  
  1107.  
  1108.  
  1109.  
  1110.  
  1111. //////////////////////////////////////   22 uni 3 zadacha exam score  / rezultat  broi studenti i sredna ocenka ///////////
  1112.  
  1113.  
  1114. using System;
  1115. using System.Collections.Generic;
  1116. using System.Linq;
  1117. using System.Text;
  1118.  
  1119. namespace ConsoleApplication4
  1120. {
  1121.     class Program
  1122.     {
  1123.         static void Main(string[] args)
  1124.         {
  1125.             SortedDictionary<string, SortedSet<string>> dataDictionary =
  1126.                                                      new SortedDictionary<string, SortedSet<string>>();
  1127.  
  1128.             SortedDictionary<string, double> dataIp =
  1129.                                                       new SortedDictionary<string, double>();
  1130.  
  1131.  
  1132.             int dataLinesNumber = int.Parse(Console.ReadLine());
  1133.             string lineContents = String.Empty;
  1134.             string[] lineTokens;
  1135.             string stud = "";
  1136.             string ExamScore = String.Empty;
  1137.             double sredno = 0;
  1138.             int count = 0;
  1139.             for (int i = 0; i < dataLinesNumber; i++)
  1140.             {
  1141.                 lineContents = Console.ReadLine();
  1142.                 lineTokens = lineContents.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
  1143.                 stud = (lineTokens[0]) + " " + (lineTokens[1]);
  1144.                 ExamScore = lineTokens[2];
  1145.                 sredno = double.Parse(lineTokens[3]);
  1146.  
  1147.                 if (!dataDictionary.ContainsKey(ExamScore))
  1148.                 {
  1149.                     dataDictionary[ExamScore] = new SortedSet<string>();
  1150.                     count++;
  1151.                     dataDictionary[ExamScore].Add(stud);
  1152.                 }
  1153.                 else
  1154.                 {
  1155.                     dataDictionary[ExamScore].Add(stud);
  1156.                 }
  1157.                 //////////////// 2 dictonary
  1158.                 if (!dataIp.ContainsKey(ExamScore))
  1159.                 {
  1160.                     dataIp[ExamScore] =  sredno;        
  1161.                 }
  1162.                 else
  1163.                 {
  1164.                     dataIp[ExamScore] += sredno;
  1165.                 }
  1166.             }
  1167.  
  1168.  
  1169.            
  1170.             ///////////////  output
  1171.  
  1172.             bool isFirstPair = true;
  1173.             double unt = 0;
  1174.             double avg = 0;
  1175.  
  1176.             int Index = 0;
  1177.  
  1178.             foreach (var dataPair in dataDictionary)
  1179.             {
  1180.                 unt = 0;
  1181.                 Console.Write(dataPair.Key + " -> ");
  1182.                 Console.Write("[");
  1183.  
  1184.                 isFirstPair = true;
  1185.                 foreach (var ku in dataPair.Value)
  1186.                 {
  1187.                     if (isFirstPair)
  1188.                     {
  1189.                         Console.Write("{0}", ku);
  1190.                         unt++;
  1191.                         isFirstPair = false;
  1192.                     }
  1193.                     else
  1194.                     {
  1195.                         Console.Write(", {0}", ku);
  1196.                         unt++;
  1197.                     }
  1198.                 }
  1199.                 Console.Write("]; ");
  1200.                 for (int i = Index; i < dataIp.Keys.Count - ((count-1) - Index); i++)
  1201.                 {
  1202.                     avg = dataIp.ElementAt(i).Value / unt;
  1203.                    // Console.WriteLine(dataIp.ElementAt(i).Value);
  1204.                     Console.Write("avg =  {0:0.00}", avg);  
  1205.                 }
  1206.  
  1207.                 Index++;
  1208.                 Console.WriteLine();      
  1209.             }
  1210.                      
  1211.  
  1212.         }
  1213.     }
  1214. }
  1215.  
  1216. ///////////// 2 reshenie na tazi gornata zadacha / 22 uni exam score  ///////////////////////////////////////////////
  1217.  
  1218.  
  1219. using System;
  1220. using System.Collections.Generic;
  1221. using System.Globalization;
  1222. using System.Linq;
  1223. using System.Threading;
  1224. class ExamScore
  1225. {
  1226.     static void Main()
  1227.     {
  1228.         Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
  1229.  
  1230.         string firstLine = Console.ReadLine();
  1231.         string secondLine = Console.ReadLine();
  1232.         string thirdLine = Console.ReadLine();
  1233.  
  1234.         SortedDictionary<int, SortedDictionary<string, double>> dataInfo = new SortedDictionary<int, SortedDictionary<string, double>>();
  1235.         string inputLine = String.Empty;
  1236.         string[] inputTokens;
  1237.        
  1238.         int examScore = 0;
  1239.         string name = String.Empty;
  1240.         double grade = 0;
  1241.         while (true)
  1242.         {
  1243.             inputLine = Console.ReadLine();
  1244.             inputTokens = inputLine.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
  1245.  
  1246.             if (inputTokens.Length < 3)
  1247.             {
  1248.                 break;
  1249.             }
  1250.  
  1251.             name = inputTokens[0].Trim();
  1252.             examScore = int.Parse(inputTokens[1].Trim());
  1253.             Console.WriteLine(inputTokens[2].Trim());
  1254.             string number = inputTokens[2].Trim();
  1255.             grade = double.Parse(number);
  1256.  
  1257.             if (!dataInfo.ContainsKey(examScore))
  1258.             {
  1259.                 dataInfo.Add(examScore, new SortedDictionary<string, double>());
  1260.             }
  1261.             dataInfo[examScore].Add(name, grade);
  1262.         }
  1263.  
  1264.         foreach (var currentExamScore in dataInfo)
  1265.         {
  1266.             Console.WriteLine("{0} -> [{1}]; avg={2:F2}", currentExamScore.Key, String.Join(", ", currentExamScore.Value.Keys), currentExamScore.Value.Values.Average());
  1267.         }
  1268.     }
  1269. }
  1270.  
  1271.  
  1272. 21 septemvri  EVEning  04.Ofisse stufff    //////////////////////////////////////////////////////////////////////////
  1273.  
  1274.  
  1275. using System;
  1276. using System.Collections.Generic;
  1277. using System.Linq;
  1278. using System.Text;
  1279. using System.Threading.Tasks;
  1280.  
  1281. namespace ConsoleApplication28
  1282. {
  1283.     internal class Program // Nasko Lapchev
  1284.     {
  1285.         private static void Main(string[] args)
  1286.         {
  1287.             // databases
  1288.             SortedDictionary<string,
  1289.              Dictionary<string, List<double>>> dataDictionary =
  1290.                  new SortedDictionary<string, Dictionary<string, List<double>>>(); // тук събираме студенти, предмети, оценки
  1291.  
  1292.             // тук слагаме накрая форматираните за печат резултати от събраната информация
  1293.             Dictionary<string, HashSet<string>> finals = new Dictionary<string, HashSet<string>>();
  1294.  
  1295.             //SortedDictionary<string, SortedDictionary<string, double>> dataO =
  1296.             //new SortedDictionary<string, SortedDictionary<string, double>>();
  1297.  
  1298.             // input
  1299.             int dataLinesNumber = int.Parse(Console.ReadLine());
  1300.  
  1301.             // declarations - страхотна идея - дава яснота на кода по-нататък
  1302.             string lineContents = String.Empty;
  1303.             string[] lineTokens;
  1304.             string student = "";
  1305.             string predmet = String.Empty;
  1306.             int ocenka = 0;
  1307.  
  1308.             // reading and parsing the lines
  1309.             // имаме 3 основни случая:
  1310.             // 1. такъв студент още не е добавян:
  1311.             // * правим List<double> за оценките му, и прибавяме оценката към този лист
  1312.             // * правим SortedDictionary<string, List<double>> studentData, и към него прибавяме предмета, и списъка с оценки (списък за да можем да прибавим и следващи оценки ако се появят
  1313.             // * чак сега вече можем да прибавим към  dataDictionary.Add(student, studentData);
  1314.             // 2. Вече има такъв студент додразбира се че и SortedDictionary<string, List<double>> studentData вече има, тъй като този речник се прибавя заедно със студента),
  1315.             // но предмета е нов: правим List<double> ocenki = new List<double>();, и прибавяме dataDictionary[student].Add(predmet, ocenki);
  1316.             // 3. има такъв студент, има такъв предмет, само оценката е нова
  1317.             // тогава: dataDictionary[student][predmet].Add(ocenka);
  1318.  
  1319.             for (int i = 0; i < dataLinesNumber; i++)
  1320.             {
  1321.                 lineContents = Console.ReadLine();
  1322.                 lineTokens = lineContents.Split(new char[] { ' ', '|', '-' }, StringSplitOptions.RemoveEmptyEntries);
  1323.                 student = lineTokens[0];
  1324.  
  1325.                 predmet = lineTokens[2];
  1326.                 ocenka = int.Parse(lineTokens[1]);
  1327.  
  1328.                 if (!dataDictionary.ContainsKey(student))
  1329.                 {
  1330.                     // ако в речника още няма такъв студент - няма как да прибавяме към него, трябва първо да го създадем
  1331.                     // същото с информацията за студента (SortedDictionary<string, List<double>> studentData) -
  1332.                     // използвах твоята идея за речника предмет-оценка, но го развих в предмет-оценки: за да може в един List<double> с оценки да пълним всички оценки
  1333.                     // между другото - за разлика от теб щях да се сетя че трябва оценките да са double - не по рано от 1 час селд като съм почнала да пиша кода :)
  1334.                     Dictionary<string, List<double>> studentData = new Dictionary<string, List<double>>();
  1335.                     List<double> ocenki = new List<double>(); // ако искаш може да смениш "ocenka/i" с grade/s
  1336.  
  1337.                     ocenki.Add(ocenka);
  1338.                     studentData.Add(predmet, ocenki);
  1339.                     dataDictionary.Add(student, studentData); // чак сега вече можем да добавим нов студент в речника
  1340.                 }
  1341.  
  1342.                 else if (dataDictionary.ContainsKey(student))
  1343.                 {
  1344.                     if (!dataDictionary[student].ContainsKey(predmet))
  1345.                     {
  1346.                         //dataDictionary[student][predmet] = new List<double>(); // мисля че няма да можем да прибавим оценки ако няма такъв студент и ние още не сме го добавили
  1347.                         // иначе казано, за да го има студента вече в речника, тяй е бил добавен заедно с SortedDictionary<string, List<double>> studentData, и там вече си има друг предмет, с други оценки
  1348.                         // остава само да добавим във вътрешня речник studentDatа нов предмет, с оценките към него
  1349.                         List<double> ocenki = new List<double>();
  1350.                         ocenki.Add(ocenka);
  1351.                         dataDictionary[student].Add(predmet, ocenki);
  1352.                     }
  1353.                     else if (dataDictionary[student].ContainsKey(predmet))
  1354.                     {
  1355.                         // за да го има предмета, той е бил добавен с List<double> с оценки, сега остава само да прибавим още една оценка
  1356.                         dataDictionary[student][predmet].Add(ocenka);
  1357.                     }
  1358.                 }
  1359.             }
  1360.  
  1361.  
  1362.             // сега идеяата е точно както ти попита: да се подготвим за печатане, ще превърнем всичката информация за студента в един форматиран стринг
  1363.             foreach (var pair in dataDictionary)
  1364.             {
  1365.                 HashSet<string> infoPoPredmeti = new HashSet<string>();
  1366.                 foreach (var pair2 in pair.Value) // трябва ни само информацияята за студента, без самия студент
  1367.                 {
  1368.                     string predmet_srednaocenka = String.Format("{1:F2}-{0}", pair2.Value.Sum(), pair2.Key); // така форматираме с колко знака след десетичната точка ще се печата средната оценка
  1369.                     //  и за всеки предмет ще получим нещо такова: "history – 5.00"
  1370.  
  1371.                     infoPoPredmeti.Add(predmet_srednaocenka); // тук са събрани всички стрингове от типа "history – 5.00", за един студент само
  1372.                 }
  1373.                 finals.Add(pair.Key, infoPoPredmeti); // тук прибавяме студента, със съответната infoPoPredmeti
  1374.             }
  1375.  
  1376.             foreach (var pair in finals)
  1377.             {
  1378.                 string infoZaStudenta = string.Join(", ", pair.Value);
  1379.                 Console.WriteLine("{0}: {1}", pair.Key, infoZaStudenta);
  1380.             }
  1381.         }
  1382.     }
  1383. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement