Check List for duplications with optional words to exclude

后端 未结 4 1338
無奈伤痛
無奈伤痛 2021-01-20 03:31

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

4条回答
  •  广开言路
    2021-01-20 04:22

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

提交回复
热议问题