Is there a type that includes both: List<T> and also HashSet<T>?

Viewed 80

I have two methods that display: one a List of items and one a HashSet of items. The methods are identical. Is there a way to write the method with a parameter type so that I can use the same method regardless of the type of the argument passed to the method: List<T> or HashSet<T>?

The methods are:

    public static void DisplayList<T>(List<T> list)
    {
        int i = 0;
        foreach (T item in list)
        {
            Console.Write(item.ToString());
            if (i < list.Count - 1)
            {
                Console.Write(", ");
            }
            i++;
        }
        Console.WriteLine();
    }

    public static void DisplayHashSet<T>(HashSet<T> set)
    {
        int i = 0;
        foreach (T item in set)
        {
            Console.Write(item.ToString());
            if (i < set.Count - 1)
            {
                Console.Write(", ");
            }
            i++;
        }
        Console.WriteLine();
    }
2 Answers

You could use the ICollection<T> interface:

public static void DisplayHashSet<T>(ICollection<T> col)
{
    int i = 0;
    foreach (T item in col)
    {
        Console.Write(item.ToString());
        if (i < col.Count - 1)
        {
            Console.Write(", ");
        }
        i++;
    }
    Console.WriteLine();
}

According to List<T> and HashSet<T> documentation both implement ICollection<T> and IReadOnlyCollection<T>, you can use any of these interfaces because they have Count property.

Since you aren't modifying the collection, only displaying it, IReadOnlyCollection<T> looks better here

public static void DisplayCollection<T>(IReadOnlyCollection<T> collection)
{
    int i = 0;
    foreach (T item in collection)
    {
        Console.Write(item.ToString());
        if (i < collection.Count - 1)
        {
            Console.Write(", ");
        }
        i++;
    }
    Console.WriteLine();
}

However, if you'll need just a string representation of collection, string.Join method with overload accepting IEnumerable<T> allows you to do that in one line

var list = new List<int>() { 1, 2, 3, 4 };
var display = string.Join(", ", list);
Console.WriteLine(display);

The code above will print 1, 2, 3, 4, which is the same with DisplayCollection<T> method above

Related