Advertisement
KOTIK_HA_MAT-MEXE

GroupBy_2

Mar 28th, 2017
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.21 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 ConsoleApplication17
  8. {
  9.     class Program
  10.     {
  11.         public static IEnumerable<IEnumerable<T>> GroupBy<T, F>(IEnumerable<T> collection, Func<T, F> rule)
  12.         {
  13.             var dicResult = new Dictionary<F, List<T>>();
  14.             foreach(var e in collection)
  15.             {
  16.                 var functionValue = rule(e);
  17.                 if (!dicResult.ContainsKey(functionValue))
  18.                 {
  19.                     dicResult.Add(functionValue, new List<T> { e});
  20.                 }
  21.                 else
  22.                 {
  23.                     dicResult[functionValue].Add(e);
  24.                 }
  25.             }
  26.             return dicResult.Values ;
  27.         }
  28.         static void Main(string[] args)
  29.         {
  30.             var list = new List<string>()
  31.             {
  32.                 "abc","bcd","d","f","gfd","2","fsdfsdfsdf","b", "gaa", "22"
  33.             };
  34.             Func<string, int> f = line => line.Length;
  35.             Func<string, char> g = line => line[0];
  36.             var result = GroupBy(list, f);
  37.             var result2 = GroupBy(list, g);
  38.         }
  39.     }
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement