How to convert this piece of code in Generics?

I have the following extension method that takes a list and converts it to a comma separated string:

    static public string ToCsv(this List<string> lst)
    {
        const string SEPARATOR = ", ";
        string csv = string.Empty;

        foreach (var item in lst)
            csv += item + SEPARATOR;

        // remove the trailing separator
        if (csv.Length > 0)
            csv = csv.Remove(csv.Length - SEPARATOR.Length);

        return csv;
    }

I want to do something similar, but apply it to a list (instead of a String list), however the compiler cannot solve for T:

    static public string ToCsv(this List<T> lst)
    {
        const string SEPARATOR = ", ";
        string csv = string.Empty;

        foreach (var item in lst)
            csv += item.ToString() + SEPARATOR;

        // remove the trailing separator
        if (csv.Length > 0)
            csv = csv.Remove(csv.Length - SEPARATOR.Length);

        return csv;
    }

What am I missing?

+3
source share
4 answers

First, a method declaration should be:

public static string ToCsv<T>(this List<T> list) { // }

Note that the method must be parameterized; it is <T>after the method name.

Secondly, do not reinvent the wheel. Just use String.Join:

public static string ToCsv<T>(this IEnumerable<T> source, string separator) {
    return String.Join(separator, source.Select(x => x.ToString()).ToArray());
}

public static string ToCsv<T>(this IEnumerable<T> source) {
    return source.ToCsv(", ");
}

Note that I went on a date and generalized the method further by accepting IEnumerable<T>instead List<T>.

.NET 4.0 :

public static string ToCsv<T>(this IEnumerable<T> source, string separator) {
    return String.Join(separator, source.Select(x => x.ToString());
}

public static string ToCsv<T>(this IEnumerable<T> source) {
    return source.ToCsv(", ");
}

source.Select(x => x.ToString()) .

, . " " .

+8

static public string ToCsv<T>(this List<T> lst){ ...
+7

Your function requires a common parameter:

static public string ToCsv<T>(this List<T> lst)
                          ^^^
+3
source

You can make it more general and use IEnumerable instead of List <T>, after all, you are not using any list specific methods

public static string ToCsv<T>(this IEnumerable lst);
+2
source

Source: https://habr.com/ru/post/1728543/


All Articles