How to loop through a list of classnames in C#

83 views Asked by At

I'm working on a template-based C# application.
This application saves entries to a database, using the procedure database.SaveChanged().

I would like to see the list of things which are to be changed, which can be done, using the following method:

IList<T> GetChanged<T>() where T : class;

This means that I could do this as follows:

foreach (var t in database.GetChanged<Alarm>())
{
    log.Debug($"DB Change=[{t}]");
}
foreach (var t in database.GetChanged<Area>())
{
    log.Debug($"DB Change. ClassName=[{t.GetType()}], Change=[{t}]");
}
...

As I have tens of classnames (Alarm and Area are just two out of the fifty-three cases), I would like to do this in an easier way, something like:

List<ClassNames> Class_List= {Alarm, Area, ..., Server.Domain.ClassName, ...}; 
// indeed, namespaces are possible

foreach (var entry in Class_List)
{
    foreach (var t in database.GetChanged<entry>())
    {
        log.Debug($"DB Change. ClassName=[{entry}], Change=[{t}]");

    }
}
1

There are 1 answers

4
Jeroen van Langen On BEST ANSWER

It would probably be possible to call the GetChanged<T>() via reflection and fillin the T.

But I think I would create a construction like:

// put all results in a list
var classes = new List<IEnumerable<CommonBaseClass>> { 
    database.GetChanged<Alarm>(),
    database.GetChanged<Area>()
};

foreach (var entry in classes)
{
    foreach (var t in entry)
    {
        log.Debug($"DB Change. ClassName=[{entry}], Change=[{t}]");
    }
}

But, I'm not able to test it here. (things like covariance)

Well, you can waste a lot of time on these kinds of things by fumbling.