[Solved] SelectMany Linq [closed]


Check the reference source from Microsoft here

Following is the SelectMany overload being utilized

        public static IEnumerable<TResult> SelectMany<TSource, TCollection, TResult>(this IEnumerable<TSource> source, Func<TSource, IEnumerable<TCollection>> collectionSelector, Func<TSource, TCollection, TResult> resultSelector) 
        {
            if (source == null) throw Error.ArgumentNull("source");
            if (collectionSelector == null) throw Error.ArgumentNull("collectionSelector");
            if (resultSelector == null) throw Error.ArgumentNull("resultSelector");
            return SelectManyIterator<TSource, TCollection, TResult>(source, collectionSelector, resultSelector);
        }

        static IEnumerable<TResult> SelectManyIterator<TSource, TCollection, TResult>(IEnumerable<TSource> source, Func<TSource, IEnumerable<TCollection>> collectionSelector, Func<TSource, TCollection, TResult> resultSelector) 
        {
            foreach (TSource element in source) 
            {
                foreach (TCollection subElement in collectionSelector(element)) 
                {
                    yield return resultSelector(element, subElement);
                }
            }
        }

How its working (this is also form of data flattening)

  1. Similar to a concentric for / foreach loops, traversing trough two collections and creating a combined list, which has the complexity of O(N^2)
  2. First we supply the number list as the IEnumerable<TSource>
  3. Add a Func, where for each number we supply the animal list
  4. Finally just get the result as the combined anonymous collection, where for each number an animal is added and thus the result is like

      n    a
    
      10   cat 
      10   dog 
      10   donkey 
      20   cat 
      20   dog 
      20   donkey 
    

solved SelectMany Linq [closed]