mardi 1 février 2022

Improving code with reflection and generics

With the following code, how could I improve its readability using reflection and generics? It's a lot of repeated code, but I'm new to these concepts. "dl" is an interface but I'm not sure why I can't get access to the properties I want with .getType().getProperties(), it returns an empty list.

if (entity == "SERVICE")
{
    if (filter == "Active == 1")
    {
        foreach (var service in dl.Services.List().Where(x => x.Active).OrderBy(x => x.Name))
            tmpReturn.Add(service.ID, service.Name);

        return tmpReturn;
    }

    foreach (var service in dl.Services.List().OrderBy(x => x.Name))
        tmpReturn.Add(service.ID, service.Name);

    return tmpReturn;
}

if (entity == "CAMPAIGN")
{
    if (filter == "Active == 1")
    {
        foreach (var campaign in dl.Campaigns.List().Where(x => x.Active).OrderBy(x => x.Name))
            tmpReturn.Add(campaign.ID, campaign.Name);

        return tmpReturn;
    }

    foreach (var campaign in dl.Campaigns.List().OrderBy(x => x.Name))
        tmpReturn.Add(campaign.ID, campaign.Name);

    return tmpReturn;
}

if (entity == "AGENT")
{
    if (condition == "Active != ")
    { 
        if (value == "1")
        { 
            foreach (var agent in dl.Agents.List().OrderBy(x => x.Name))
                tmpReturn.Add(agent.ID, agent.Name);

            return tmpReturn;
        }

        foreach (var agent in dl.Agents.List().Where(x => x.Active).OrderBy(x => x.Name))
            tmpReturn.Add(agent.ID, agent.Name);

        return tmpReturn;
    }
    else if (condition == "Active == ")
    {
        if (value == "1")
        {
            foreach (var agent in dl.Agents.List().Where(x => x.Active).OrderBy(x => x.Name))
                tmpReturn.Add(agent.ID, agent.Name);

            return tmpReturn;
        }

        foreach (var agent in dl.Agents.List().OrderBy(x => x.Name))
            tmpReturn.Add(agent.ID, agent.Name);

        return tmpReturn;
    }
}




Aucun commentaire:

Enregistrer un commentaire