Home > Blockchain >  Is there a way to find out whether a generic type is integer and count all elements inside the colle
Is there a way to find out whether a generic type is integer and count all elements inside the colle

Time:02-28

I wrote my on generic class for Binary Search Tree, I need to define a method that searches for all even numbers in a Tree. Here is how i define a tree:

class BST<T> : ICollection<T> where T : IComparable<T> {

    public int CountEven() {
        if (root != null) return ccount(root, 2);

        return 0;
    }

    private int ccount(Node root, int div) {
        Type itemType = typeof(T);

        if (itemType == typeof(int) && root != null) {

            if (root.data % div == 0) {
                //error: operation / cannot be applied to operands of type T and int
                return 1   ccount(root.left, div)   ccount(root.right, div);
            }

            else { return ccount(root.left, div)   ccount(root.right, div); }
        }

        return 0;
    }
}

CodePudding user response:

To avoid the error, you could adjust your if statement:

if (itemType == typeof(int) && root?.data is int intData)

Afterwards you can work with the int typed variable intData.

Also, I guess you are using the wrong operator for the even check. You should use something like that:

if (intData % div == 0)

Combined your ccount() method should look something like:

private int ccount(Node root, int div)
{
  Type itemType = typeof(T);
  if (itemType == typeof(int) && root?.data is int intData)
  {
    if (intData % div == 0)
    {
      return 1   ccount(root.left, div)   ccount(root.right, div);
    }
    else
    {
      return ccount(root.left, div)   ccount(root.right, div);
    }
  }
  return 0;
}

CodePudding user response:

 public int CountEven()
{
    if (root != null)
        return  ccount(root, 2);
    return 0;
}

private int ccount(Node root, int div)
{
    Type itemType = typeof(T);
    if (root == null)
        return 0;
    if ( itemType == typeof(int) && root.data is int intData)
    {
        int add = 0;
        if (intData % div == 0)
            add = 1;
            return add  ccount(root.left, div)   ccount(root.right, div);
    }
  
    return 0;
}
  • Related