CSharp examples for System.Collections.Generic:ICollection
Adds the missing items to the collection. Deals with null collections
using System.Linq; using System.Collections.Generic; using System;// w w w .ja v a 2 s.c o m public class Main{ /// <summary> /// Adds the missing items to the collection. /// Deals with null collections /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">The source.</param> /// <param name="items">The items.</param> /// <param name="validationFunc">The validation function.</param> /// <remarks> /// The missing item is only added if the validation func returns true /// </remarks> public static void SafeAddMissing<T>(this ICollection<T> source, IEnumerable<T> items, Func<T, bool> validationFunc) { if (source == null || items == null || validationFunc == null) return; try { if (items != null && items.Count() > 0) { foreach (T item in items) { if (!source.Contains(item) && validationFunc.Invoke(item)) source.Add(item); } } } catch (Exception) { //TODO: Log this error } } /// <summary> /// Adds the missing items to the collection. /// Deals with null collections /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">The source.</param> /// <param name="items">The items.</param> public static void SafeAddMissing<T>(this ICollection<T> source, IEnumerable<T> items) { SafeAddMissing<T>(source, items, new Func<T, bool>(ShouldAddItem)); } }