Advertisement
Razali

HasDistinct

Jun 3rd, 2020
1,194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.26 KB | None | 0 0
  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. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement