Check List<T> for duplications with optional words to exclude

  • A+
Category:Languages

I have a method as below. Method return either false/true either when list contains duplicates or not. I would like to extend my method to say for instance (optional) that i want to exclude specific items from check. For instance i want to check entire list as it is now or i want to say for instance exclude: string.empty items or for instance string.empty and "some word". Is it possible?

public static bool IsListContainsDuplicates<T>(List<T> list) {     return list.GroupBy(n => n).Any(c => c.Count() > 1); } 

 


public static bool ContainsDuplicates<T>(this IEnumerable<T> items, IEnumerable<T> itemsToExclude = null) {     if (itemsToExclude == null) itemsToExclude = Enumerable.Empty<T>();     return items.Except(itemsToExclude)                 .GroupBy(n => n)                 .Any(c => c.Count() > 1); } 

But i'd prefer this implementation because it's more performant:

public static bool ContainsDuplicates<T>(this IEnumerable<T> items, IEnumerable<T> itemsToExclude = null) {     if (itemsToExclude == null) itemsToExclude = Enumerable.Empty<T>();     HashSet<T> set = new HashSet<T>();     return !items.Except(itemsToExclude).All(set.Add); } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: