Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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);
}
like image 912
DinoDin2 Avatar asked Dec 14 '22 14:12

DinoDin2


1 Answers

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);
}
like image 71
Tim Schmelter Avatar answered Dec 16 '22 04:12

Tim Schmelter