Advertisement
NastySwipy

Dictionaries_Lambda_Expressions_LINQ - 08. Logs Aggregator

Apr 26th, 2018
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.60 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. namespace _07b_Dictionaries_Lambda_Expressions_LINQ_Exercises
  6. {
  7.     class Dictionaries_Lambda_Expressions_LINQ_Exercises
  8.     {
  9.        static void Main(string[] args)
  10.         {
  11.             Dictionary<string, Dictionary<string, int>> logs = new Dictionary<string, Dictionary<string, int>>();
  12.             int n = int.Parse(Console.ReadLine());
  13.  
  14.             for (int i = 0; i < n; i++)
  15.             {
  16.                 string line = Console.ReadLine();
  17.                 string[] tokens = line.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);
  18.                 string ip = tokens[0];
  19.                 string user = tokens[1];
  20.                 int duration = int.Parse(tokens[2]);
  21.  
  22.                 if (!logs.ContainsKey(user))
  23.                 {
  24.                     logs.Add(user, new Dictionary<string, int>());
  25.                 }
  26.                 if (!logs[user].ContainsKey(ip))
  27.                 {
  28.                     logs[user].Add(ip, duration);
  29.                 }
  30.                 else
  31.                 {
  32.                     logs[user][ip] += duration;
  33.                 }
  34.             }
  35.             foreach (var log in logs.OrderBy(x => x.Key))
  36.             {
  37.                 string username = log.Key;
  38.                 int totalDuration = log.Value.Sum(x => x.Value);
  39.                 string[] ips = log.Value
  40.                     .Keys
  41.                     .OrderBy(x => x)
  42.                     .ToArray();
  43.                 Console.WriteLine($"{username}: {totalDuration} [{string.Join(", ", ips)}]");
  44.             }
  45.         }
  46.     }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement