Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic method for converting string array into list

Tags:

c#

.net

generics

I would like to create a function that will return list of type that is specified by me at run time. I tried something along this line:

  public static List<T> GetMyList<T>(string[] itemList)
  {
     List<T>  resultList = new List<T>(itemList.Length);
     return resultList.AddRange(itemList);
  }

But this doesn't work. Obviously I don't fully understand how to pass a type to be converted to. Any help would be appreciated it.

Edit: It looks like that it is not possible, but here is more info. String array will contain numbers and I would like to convert those numbers sometimes into int, sometimes into short. Idea behind is to have a generic function that will attempt to convert items into whatever type list I tell it.

like image 944
krul Avatar asked Mar 22 '26 04:03

krul


1 Answers

You need to provide a method to convert a string into a T - you can do this using a Func<string, T>:

public static List<T> GetMyList<T>(string[] itemList, Func<string, T> conversionFunc)
{
    return itemList.Select(conversionFunc).ToList();
}

e.g.

List<int> ints = GetMyList(new[] { "1", "2", "3" }, s => int.Parse(s));
like image 177
Lee Avatar answered Mar 24 '26 19:03

Lee