Home > Net >  Problem with implementation generic filter method which should return TSource[]
Problem with implementation generic filter method which should return TSource[]

Time:05-04

I have created my implementation of Filter method, but unfortunately my solution is not good, because most of my unit tests are not passed. Can someone explain me how it should be done ? Method used with my own interface IPredicate, and I don't know how to implement methods bool verify() which implement interface IPredicate and ContainsDigitValidator. There is my interface.

    /// <summary>
    /// Defines a generalized predicate an object.
    /// </summary>
    /// <typeparam name="T">The type of the object to compare against the criteria. This type parameter is contravariant.</typeparam>
    public interface IPredicate<in T>
    {
        /// <summary>
        /// Represents the method that defines a set of criteria and determines whether the specified object meets those criteria.
        /// </summary>
        /// <param name="obj">The object to compare against the criteria.</param>
        /// <returns>true if obj meets the criteria defined within the method; otherwise, false.</returns>
        bool Verify(T obj);
    }

There is a class ContainsDigitPredicateAdapter

public class ContainsDigitPredicateAdapter : IPredicate<int>
    {
        private readonly ContainsDigitValidator validator;

        public ContainsDigitPredicateAdapter(ContainsDigitValidator? validator)
        {
            this.validator = validator;
        }

        public bool Verify(int obj)
        {
            return obj.CompareTo(this.validator.Digit) == 0;
        }
    }
        

There is a class ContainsDigitValidator

    public class ContainsDigitValidator
    {
        public ContainsDigitValidator()
        {
        }

        public int Digit
        {
            get;
            set;
        }

        public bool Verify(int value)
        {
            return value.CompareTo(this.Digit) == 0;
        }
    }

CodePudding user response:

I think you should use

return value.ToString().Contains(Digit.ToString());

CodePudding user response:

For filtering you can use your IPredicate as is with Linq:

IEnumerable<TSource> source = ... // get source
IPredicate<TSource> predicate = ... // get predicate

var filtered = source.Where(predicate.Verify).ToArray();
  • Related