Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Security.Policy;
- namespace GroupBy
- {
- public static class Program
- {
- public static void Main()
- {
- var workers = new List<People>()
- {
- new People("Bob", 18),
- new People("Anna", 24),
- new People("Petya", 18),
- new People("Misha", 18),
- };
- var groupWorkersByAge = workers.MyGroupBy(worker => worker.Age);
- foreach (var pair in groupWorkersByAge)
- {
- Console.Write("{0}: ", pair.Key);
- foreach (var value in pair.Value)
- {
- Console.Write("{0} ", value.Name);
- }
- Console.WriteLine();
- }
- }
- public static Dictionary<TKey, List<TValue>> MyGroupBy<TKey, TValue>(
- this IEnumerable<TValue> collection, Func<TValue, TKey> keySelector)
- {
- var groups = new Dictionary<TKey, List<TValue>>();
- foreach (TValue value in collection)
- {
- var key = keySelector(value);
- if (!groups.ContainsKey(key)) groups[key] = new List<TValue>();
- groups[key].Add(value);
- }
- return groups;
- }
- }
- public class People
- {
- public string Name { get; }
- public int Age { get; }
- public People(string name, int age)
- {
- Name = name;
- Age = age;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement