Removes all the items filtered by a predicate. Deals with null IList - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:IList

Description

Removes all the items filtered by a predicate. Deals with null IList

Demo Code


using System.Linq;
using System.Collections.Generic;
using System.Collections;
using System;//w w  w . j av  a  2s  .c  o m
using Cirrious.CrossCore.Platform;

public class Main{
        /// <summary>
        /// Removes all the items filtered by a predicate.
        /// Deals with null IList
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source">The source.</param>
        /// <param name="filterPredicate">The filter predicate.</param>
        /// <returns></returns>
        public static bool SafeRemoveAll<T>(this IList<T> source, Func<T, bool> filterPredicate)
        {
            try
            {
                var toRemove = source.Where(filterPredicate).ToList();
                toRemove.SafeForEach(r =>
                {
                    if (source.Contains(r))
                        source.Remove(r);
                });

                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
        /// <summary>
        /// Applies the action to every item in the list
        /// Deals with null IList
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source">The source.</param>
        /// <param name="action">The action.</param>
        public static IList<T> SafeForEach<T>(this IList<T> source, Action<T> action)
        {
            if (source != null && source.Count > 0)
            {
                foreach (var item in source)
                {
                    action(item);
                }
            }

            return source;
        }
}

Related Tutorials