C # Convert list <object> to source type without explicit cast

I am having trouble converting a list object back to its original type without an explicit cast. My intention is to generalize the methods so that I can go through different types of databases, such as Man or Company. I have no problem getting the values โ€‹โ€‹through reflection, but I need to convert the actual list back to the original type List<typeT> instead of List<object> in the method to which I pass it. I know the following methods:

  SomeList.ConvertAll(x => (typeT)x); SomeList.Cast<typeT>().ToList(); 

However, for these methods I will have to explicitly impose typeT. I tried the following:

 formatted1.ConvertAll(x => Convert.ChangeType(x, typeT)); 

and

 List<dynamic> newList = new List<dynamic>(); foreach (var p in SomeList) { newList.Add(Convert.ChangeType(p, typeT); } 

There is no success so far. Maybe I should have another game plan to summarize these methods. right now I am passing lists as follows:

 public string returnJson(List<object> entity, string someString) { } 
+4
source share
3 answers

It seems that creating returnJson generic will solve most of these problems:

 public string returnJson<T>(List<T> entity, string someString) { } 

Now returnJson can be used in general form, for example:

 returnJson<Company>(listOfCompanies, "someString"); 

and

 returnJson<Person>(listOfPersons, "someOtherString"); 

You can still reflect objects, but a list is always a list of the type you need at compile time. No casting required.

+6
source

Why not use generics, so that the calling function can do what it needs:

 public string returnJson<T>(List<T> entity, string someString) { //not sure what someString is for or why you need the type for this naming scheme JavaScriptSerializer jss = new JavaScriptSerializer(); return jss.Serialize(entity); } 
+1
source

You can use dynamic keyword and reflection to create a list.

 dynamic newList = Activator.CreateInstance(typeof(List<>).MakeGenericType(typeT)); foreach (var p in SomeList) { newList.Add(p); } CallOtherMethodOverloadedForListOfPersonCompanyEtc(newList) 
0
source

All Articles