Advertisement
Layvu

FP1

Mar 13th, 2023
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.59 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Security.Policy;
  5.  
  6. namespace GroupBy
  7. {
  8.     public static class Program
  9.     {
  10.         public static void Main()
  11.         {
  12.             var workers = new List<People>()
  13.             {
  14.                 new People("Bob", 18),
  15.                 new People("Anna", 24),
  16.                 new People("Petya", 18),
  17.                 new People("Misha", 18),
  18.             };
  19.  
  20.             var groupWorkersByAge = workers.MyGroupBy(worker => worker.Age);
  21.  
  22.             foreach (var pair in groupWorkersByAge)
  23.             {
  24.                 Console.Write("{0}: ", pair.Key);
  25.                 foreach (var value in pair.Value)
  26.                 {
  27.                     Console.Write("{0} ", value.Name);
  28.                 }
  29.                 Console.WriteLine();
  30.             }
  31.         }
  32.  
  33.         public static Dictionary<TKey, List<TValue>> MyGroupBy<TKey, TValue>(
  34.             this IEnumerable<TValue> collection, Func<TValue, TKey> keySelector)
  35.         {
  36.             var groups = new Dictionary<TKey, List<TValue>>();
  37.             foreach (TValue value in collection)
  38.             {
  39.                 var key = keySelector(value);
  40.                 if (!groups.ContainsKey(key)) groups[key] = new List<TValue>();
  41.                 groups[key].Add(value);
  42.             }
  43.  
  44.             return groups;
  45.         }
  46.     }
  47.  
  48.     public class People
  49.     {
  50.         public string Name { get; }
  51.         public int Age { get; }
  52.  
  53.         public People(string name, int age)
  54.         {
  55.             Name = name;
  56.             Age = age;
  57.         }
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement