Asal
Asal

Reputation: 49

How I pass the type dynamically IEnumerable<T> C#

I want to pass a object type to IEnumerable<T> at runtime.

For example, I have to get the read the CSV file and they all return different set of data.

So in case if I want use a single method but extract a different set of entity than how I can do that? In the example shown below, I want to pass different entity instead of Student:

public List<Patient> GetAcgFileData(string fullFileName) 
{
    using (var sr = new StreamReader(fullFileName)) 
    {
        var reader = new CsvReader(sr);
        ////CSVReader will now read the whole file into an enumerable
        var records = reader.GetRecords<Student>().ToList();
        return records;
    }
}

Upvotes: 0

Views: 79

Answers (1)

TerribleDev
TerribleDev

Reputation: 2245

You can make your function take in a generic

public List<T> GetAcgFileData<T>(string fullFileName) {  
    using (var sr = new StreamReader(fullFileName)) {
        var reader = new CsvReader(sr);
        ////CSVReader will now read the whole file into an enumerable
        var records = reader.GetRecords<T>().ToList();
        return records;
    }
}

Then you can call it with a type GetAcgFileData<Student>("somestring");

Upvotes: 1

Related Questions