Method with a shared collection parameter

I have a method that should accept a collection (perhaps IEnumerable<T>

or List<T>

) of any type (for example, List<int>

or List<string>

).

inside the method I need to iterate over the collection and each element is converted to a string and concatenated into one final string, like so:

"(12, 123, 22)"

      

The problem is how to determine that the parameter set can be of any type. I think this is something about generics, but I don't know much about it.

However, the thing's method definition should look something like this:

public string myMethod(List<T> list) { }

      

However, the compiler does not allow this. Could you please tell me the correct syntax?

+3


source to share


1 answer


class A
{
    public string myMethod<T>(List<T> list) { }
}

      

or

class B<T>
{
    public string myMethod(List<T> list) { }
}

      


You might want to use IEnumerable<T>

because you just need to list the sequence.




The same can be achieved with built-in functions:

IEnumerable<X> input = new List<X> { new X(), new X() };
IEnumerable<string> s = list.Select(x => x.ToString());
string result = String.Join(", ", s); // "x, x"

      

See MSDN .

+2


source







All Articles