检查表< T>用于带有可选单词的重复项以排除 [英] Check List<T> for duplications with optional words to exclude

查看:44
本文介绍了检查表< T>用于带有可选单词的重复项以排除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有如下方法.当列表是否包含重复项时,方法返回false/true.我想扩展我的方法,例如说(可选)我想从检查中排除特定项目.例如,我想按现在检查整个列表,或者我想说例如排除:string.empty项目或例如string.empty和某些单词".有可能吗?

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);
}

这篇关于检查表&lt; T&gt;用于带有可选单词的重复项以排除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆