Search code examples
c#asp.net-mvc-5generic-collections

How to populate a list of a generic class based on type?


I have a method that reads a file and populate a list of a model based on the information of this file. Currenly the file I am reading contains serverData which i populate to a list of serverModel with this code:

public static List<ServerModel> GetServerModels()
{
    List<ServerModel> models = new List<ServerModel>();

    try
    {
        var reader = new StreamReader(Helper.GetPath("Domains.ini"), Encoding.Default);


        while (!reader.EndOfStream)
        {
            try
            {
                var line = reader.ReadLine();

                string[] info = line.Split(';');

                //if(info.Count > 1)
                models.Add(new ServerModel { 
                  DomainName = info[1], 
                  ServerUrl = info[3], 
                  StatisticUrl = info[5] });
            }
            catch (Exception e)
            {

            }
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e.Message);

    }
    return models;
}

Now I have a new file that contains Maildata which I want to populate a list of maildata and return it.

I modified the code to use generic classes like so:

public List<T> GetModeldata<T>(string path)
{
    List<T> models = new List<T>();

    try
    {
        var reader = new StreamReader(path, Encoding.Default);


        while (!reader.EndOfStream)
        {
            try
            {
                var line = reader.ReadLine();

                string[] info = line.Split(';');

                if(typeof(T) == typeof(ServerModel))
                    models.Add(new ServerModel { 
                      DomainName = info[1], 
                      ServerUrl = info[3], 
                      StatisticUrl = info[5] });
            }
            catch (Exception e)
            {
                throw;
            }
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e.Message);

    }
    return models;
}

Now I can't figure out how to populate a list of maildata when I need that and how to populate a list of serverdata when I need that.

I added this check in the code:

if(typeof(T) == typeof(ServerModel))

And tried to add data to the model:

 models.Add(new ServerModel { 
   DomainName = info[1], 
   ServerUrl = info[3], 
   StatisticUrl = info[5] });

But I get

Can not convert from serverModel to T

How is this done?


Solution

  • Try this:

    T obj = (T)Activator.CreateInstance( typeof(T),
                                         new object[]{ info[1], info[3], info[5]});
    
    models.Add(obj);
    

    Edited:

    // Also you can just cast to T:
    models.Add((T)(object)(new ServerModel { 
      DomainName = info[1], 
      ServerUrl = info[3], 
      StatisticUrl = info[5] }));