i have a method, which should accept collection (perhaps IEnumerable<T> or List<T>) of any type (e.g. List<int> or List<string>).
inside of method i need to iterate collection and each element convert to string and add them together into one final string, like:
"(12, 123, 22)"
Problem is how to define that parameter collection can be of any type. I guess this is something about generics, but i do not know much about it.
However, i thing method definition should look something like this:
public string myMethod(List<T> list) { }
However, compiler does not allow it. Can you please tell me correct syntax?
class A
{
public string myMethod<T>(List<T> list) { }
}
or
class B<T>
{
public string myMethod(List<T> list) { }
}
Probably you may want to use IEnumerable<T> because you need just to enumerate over the sequence.
The same you can achieve using 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With