Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static class ListExtensions
- {
- //Usage Example: person.Names.HasDistinct(x => x.Name);
- public static bool HasDistinct<Type, TProperty>(this IEnumerable<Type> obj, Expression<Func<Type, TProperty>> propertySelector)
- {
- IEnumerable<TProperty> listOfThatProperty = obj.Select(propertySelector.Compile());
- return listOfThatProperty.Count() == listOfThatProperty.Distinct().Count();
- }
- }
- public class UnitTest1
- {
- [Fact]
- public void Test1()
- {
- PersonName personName1 = new PersonName() { Name = "Razali" };
- PersonName personName2 = new PersonName() { Name = "RuiRui" };
- Person person = new Person()
- {
- PersonNames = new PersonName[]{ personName1, personName2 }.ToList()
- };
- Assert.True(person.PersonNames.HasDistinct(p => p.Name));
- personName1 = new PersonName() { Name = "Razali" };
- personName2 = new PersonName() { Name = "Razali" };
- person = new Person()
- {
- PersonNames = new PersonName[] { personName1, personName2 }.ToList()
- };
- Assert.False(person.PersonNames.HasDistinct(p => p.Name));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement