Check List for duplications with optional words to exclude

后端 未结 4 1334
無奈伤痛
無奈伤痛 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:04

    Instead of making your method more complicated, you should open it more to combine it with others:

    public static class MyLinqMethods
    {
      public static bool HasDuplicates<T>(this IEnumerable<T> sequence)
      {
          return sequence.GroupBy(n => n).Any(c => c.Count() > 1);
      }
    }
    

    Now you can use it with Linq:

    var original = new[] { string.Empty, "Hello", "World", string.Empty };
    
    var duplicatesInOriginal = original.HasDuplicates();
    
    var duplicatesIfStringEmptyIsIgnored = original.Where(o => o != string.Empty).HasDuplicates();
    
    0 讨论(0)
  • 2021-01-20 04:08

    This will also help, using a 'params' in arguments and then doing Except()

      public static bool IsListContainsDuplicates<T>(List<T> list, params T[] optional)
            {
                return list.Except(optional).GroupBy(n => n).Any(c => c.Count() > 1);
            }
    

    You can call like this if you doesn't want to exclude anything:

    IsListContainsDuplicates(list)
    

    Else, just pass the params values, for example, if the list is an integer list then,

    IsListContainsDuplicates(list,5,4)
    
    0 讨论(0)
  • 2021-01-20 04:18

    You can use Except(). From MSDN:

    Produces the set difference of two sequences by using the default equality comparer to compare values.

    return list.Except(listToExclude).GroupBy(n => n).Any(c => c.Count() > 1);
    
    0 讨论(0)
  • 2021-01-20 04:22
    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);
    }
    
    0 讨论(0)
提交回复
热议问题