Check List for duplications with optional words to exclude

后端 未结 4 1335
無奈伤痛
無奈伤痛 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(this IEnumerable 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();
    

提交回复
热议问题