I was able to convert comma separated string to an IList<int> but how can I modify the same to get IList<T> where T will be passed as one of the input parameter?
i.e if I need IList<int> I will pass "int" as parameter, if I need IList<string> I will pass "string" as parameter.
My idea is to get the type whether it is int or string through input parameter and use reflection and convert the string to respective list
Code to convert comma separated string as IList<int>
public static IList<int> SplitStringUsing(this string source, string seperator =",")
{
return source.Split(Convert.ToChar(seperator))
.Select(x => x.Trim())
.Where(x => !string.IsNullOrWhiteSpace(x))
.Select(int.Parse).ToList();
}
Note: Above code isn't tested yet
I am looking for something like
public static IList<T> SplitStringUsing(this string source, string seperator =",", T t)
{
find the type of t and convert it to respective List
}
T tyou provide a "selector" functionFunc<string, T>and then use that in place of theint.Parse? So you could use it likeIList<int> list = "1, 2, 3, 4".SplitStringUsing(",", int.Parse);. And if you need for example doubles, you can change it toIList<double> list = "1, 2, 3, 4".SplitStringUsing(",", double.Parse);. - Corak