Here is some code, it won't compile but essentially want I want to create is a function that parses as CSV file and then converts the values in the CSV list to a specific type.
Func<string, Func<string,T>, IEnumerable<T>> parser =(string csv, Func<string, T> newFunc) =>
{
List<T> items = new List<T>();
string[] ary = csv.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
foreach (string val in ary)
{
try
{
items.Add(newFunc(val));
}
catch { }
}
return items;
}
I want this function to be generic so T is the type that I want the CSV list to be converted to. The usage of this function would be something like:
string csvList ="1,2,3";
IEnumerable<int> list = parser(csvList, (string val) => { return Convert.ToInt32(val)});
However this obviously won't work because I haven't defined T. So is it possible to define T in a similar manner to generic methods like so:
Func<T><string, Func<string,T>, IEnumerable<T>> parser =(string csv, Func<string, T> newFunc) =>
{
List<T> items = new List<T>();
string[] ary = csv.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
foreach (string val in ary)
{
try
{
items.Add(newFunc(val));
}
catch { }
}
return items;
}
And then use this like so:
string csvList ="1,2,3";
IEnumerable<int> list = parser<int>(csvList, (string val) => { return Convert.ToInt32(val)});
Is there a way of doing something like this in C#?
-- Further Edit
Thanks to those of you have respond, in the code I have written I actually use a method like you have described, but I was wondering just a general aside if it was possible to do this as Func without the need for a method call.