Ejemplo n.º 1
0
        /// <summary>
        /// Returns a sequence from a dictionary based on the result of evaluating a selector function, also specifying a default sequence.
        /// </summary>
        /// <typeparam name="TValue">Type of the selector value.</typeparam>
        /// <typeparam name="TResult">Result sequence element type.</typeparam>
        /// <param name="selector">Selector function used to pick a sequence from the given sources.</param>
        /// <param name="sources">Dictionary mapping selector values onto resulting sequences.</param>
        /// <param name="defaultSource">Default sequence to return in case there's no corresponding source for the computed selector value.</param>
        /// <returns>The source sequence corresponding with the evaluated selector value; otherwise, the default source.</returns>
        public static IEnumerable <TResult> Case <TValue, TResult>(Func <TValue> selector, IDictionary <TValue, IEnumerable <TResult> > sources, IEnumerable <TResult> defaultSource)
        {
            if (selector == null)
            {
                throw new ArgumentNullException("selector");
            }
            if (sources == null)
            {
                throw new ArgumentNullException("sources");
            }
            if (defaultSource == null)
            {
                throw new ArgumentNullException("defaultSource");
            }

            return(EnumerableEx.Defer(() =>
            {
                IEnumerable <TResult> result;
                if (!sources.TryGetValue(selector(), out result))
                {
                    result = defaultSource;
                }
                return result;
            }));
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Returns an enumerable sequence if the evaluation result of the given condition is true, otherwise returns an empty sequence.
        /// </summary>
        /// <typeparam name="TResult">Result sequence element type.</typeparam>
        /// <param name="condition">Condition to evaluate.</param>
        /// <param name="thenSource">Sequence to return in case the condition evaluates true.</param>
        /// <returns>The given input sequence if the condition evaluates true; otherwise, an empty sequence.</returns>
        public static IEnumerable <TResult> If <TResult>(Func <bool> condition, IEnumerable <TResult> thenSource)
        {
            if (condition == null)
            {
                throw new ArgumentNullException("condition");
            }
            if (thenSource == null)
            {
                throw new ArgumentNullException("thenSource");
            }

            return(EnumerableEx.Defer(() => condition() ? thenSource : Enumerable.Empty <TResult>()));
        }