SHARE
TWEET

HasDistinct

Razali Jun 3rd, 2020 (edited) 1,051 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. public static class ListExtensions
  2. {
  3.         //Usage Example: person.Names.HasDistinct(x => x.Name);
  4.         public static bool HasDistinct<Type, TProperty>(this IEnumerable<Type> obj, Expression<Func<Type, TProperty>> propertySelector)
  5.         {
  6.             IEnumerable<TProperty> listOfThatProperty = obj.Select(propertySelector.Compile());
  7.  
  8.             return listOfThatProperty.Count() == listOfThatProperty.Distinct().Count();
  9.         }
  10. }
  11. public class UnitTest1
  12. {
  13.         [Fact]
  14.         public void Test1()
  15.         {
  16.             PersonName personName1 = new PersonName() { Name = "Razali" };
  17.             PersonName personName2 = new PersonName() { Name = "RuiRui" };
  18.  
  19.             Person person = new Person()
  20.             {
  21.                 PersonNames = new PersonName[]{ personName1, personName2 }.ToList()
  22.             };
  23.  
  24.             Assert.True(person.PersonNames.HasDistinct(p => p.Name));
  25.  
  26.             personName1 = new PersonName() { Name = "Razali" };
  27.             personName2 = new PersonName() { Name = "Razali" };
  28.  
  29.             person = new Person()
  30.             {
  31.                 PersonNames = new PersonName[] { personName1, personName2 }.ToList()
  32.             };
  33.  
  34.             Assert.False(person.PersonNames.HasDistinct(p => p.Name));
  35.         }
  36. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top