Kristian Dimitrov
Kristian Dimitrov

Reputation: 53

Generic class, How to implement IComparable

TASK: Create a method that receives as argument a list of any type that can be compared and an element of the given type. The method should return the count of elements that are greater than the value of the given element. Modify your Box class to support comparing by value of the data stored. On the first line you will receive n - the number of elements to add to the list. On the next n lines, you will receive the actual elements. On the last line you will get the value of the element to which you need to compare every element in the list.

INPUT: 3 aa aaa bb

(givenElement is "aa")

OUTPUT: 2

Here is my code, i dunno how to compare them ...

public class Box<T> : IComparable<Box<T>>
{
    private T value;

    public Box(T value)
    {
        this.value = value;
    }

    public T Value
    {
        get
        {
            return this.value;
        }
        set
        {
            this.value = value;
        }
    }

    public int CompareTo(Box<T> other)
    {
        // ???
    }

    public override string ToString()
    {
        return string.Format($"{value.GetType().FullName}: {value}");
    }
}

    static void Main()
    {
        int n = int.Parse(Console.ReadLine());

        List<Box<string>> boxList = new List<Box<string>>();

        for (int i = 0; i < n; i++)
        {
            string input = Console.ReadLine();
            var box = new Box<string>(input);

            boxList.Add(box);              
        }

        string inp = Console.ReadLine();

        var elementComparer = new Box<string>(inp);


       GenericCountMethod(boxList, elementComparer);

    }
    public static int GenericCountMethod<T>(List<T> boxList, T str)
        where T : IComparable<T>
    {
        int count = 0;
        foreach (var item in boxList)
        {
            var x = item.CompareTo(str);
            // ??

        }
        return count;
    }

Upvotes: 1

Views: 731

Answers (1)

Andrii Litvinov
Andrii Litvinov

Reputation: 13182

You could apply a constraint to a class

public class Box<T> : IComparable<Box<T>> where T: IComparable<T>

and then use CompareTo implementation of value:

public int CompareTo(Box<T> other)
{
    return value.CompareTo(other.Value);
}

Upvotes: 1

Related Questions