Advertisement
uniblab

EnumerableHelper

Mar 20th, 2018
382
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.58 KB | None | 0 0
  1. using System.Linq;
  2.  
  3. public static class Enumerable {
  4.  
  5.     public static System.Collections.Generic.IEnumerable<TOuter> Except<TOuter, TInner, TKey, TResult>(
  6.         this System.Collections.Generic.IEnumerable<TOuter> outer,
  7.         System.Collections.Generic.IEnumerable<TInner> inner,
  8.         System.Func<TOuter, TKey> outerKeySelecter,
  9.         System.Func<TInner, TKey> innerKeySelecter
  10.     ) {
  11.         var comparer = System.Collections.Generic.EqualityComparer<TKey>.Default;
  12.  
  13.         var i = inner.ToDictionary( innerKeySelecter, comparer );
  14.         return outer.Where(
  15.             x => !i.ContainsKey( outerKeySelecter( x ) )
  16.         );
  17.     }
  18.  
  19.     public static System.Collections.Generic.IEnumerable<TOuter> Except<TOuter, TInner, TKey, TResult>(
  20.         this System.Collections.Generic.IEnumerable<TOuter> outer,
  21.         System.Collections.Generic.IEnumerable<TInner> inner,
  22.         System.Func<TOuter, TKey> outerKeySelecter,
  23.         System.Func<TInner, TKey> innerKeySelecter,
  24.         System.Collections.Generic.IEqualityComparer<TKey> comparer
  25.     ) {
  26.         var i = inner.ToDictionary( innerKeySelecter, comparer );
  27.         return outer.Where(
  28.             x => !i.ContainsKey( outerKeySelecter( x ) )
  29.         );
  30.     }
  31.  
  32.     public static System.Collections.Generic.IDictionary<K, V> ToDictionary<K, V>(
  33.         this System.Collections.Generic.IEnumerable<V> collection,
  34.         System.Func<V, K> keySelector,
  35.         System.Collections.Generic.IEqualityComparer<K> keyComparer
  36.     ) {
  37.         System.Collections.Generic.IDictionary<K, V> output = new System.Collections.Generic.Dictionary<K, V>( keyComparer );
  38.         foreach ( var item in collection ) {
  39.             output.Add( keySelector( item ), item );
  40.         }
  41.         return output;
  42.     }
  43.  
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement