Yoshuwa
Yoshuwa

Reputation: 21

How to shorten A LOT of IF statements in C#?

I'm doing some data filtering for each table in the database, and this database has 567 tables

so here is my filter for 1 table [Source]

 if (Context.Request.UrlReferrer.ToString().ToLower().Contains("Source"))
                    AccessControlRule("SourceID",
                        "select SourceID from Source where IsDelete = 0",
                        AccessPermission.Allow);
         else
            AccessControlRule("SourceID",
                        "select SourceID from Source where IsDelete = 1 OR IsDelete = null",
                        AccessPermission.Allow);

The snippet above filters Sources. now I'm currently writing IF statements for ALL tables, which means there's a lot of code & (copy/paste) and I'm afraid this could lead to a lot of human errors.

Do you have a way to shorten this? perhaps a loop type of process?

Thanks!

Upvotes: 0

Views: 136

Answers (1)

Milney
Milney

Reputation: 6417

Well, you've not really given enough information, but i'll bite... Assuming all your tables/code follows that same pattern, its fairly simple:

// You'll want to whitelist the tables, so you are not
// trusting user input for the table name
var tables = new List<String>() { "Source", ... };

foreach(var table in tables){
    if (Context.Request.UrlReferrer.ToString().ToLower().Contains(table)){
        AccessControlRule(
           $"{table}ID",
            "select {table}ID from {table} where IsDelete = 0", 
            AccessPermission.Allow
        );
    } else {
        AccessControlRule(
           $"{table}ID", 
            "select {table}ID from {table} where IsDelete = 1 OR IsDelete = null",
            AccessPermission.Allow
        );
    }
}

BUT - you probably don't want to actually configure anything like AccessRules or Security using the Referrer value, as it can be trivially spoofed... You are not relying on this code for some form of security are you?


Edit if your keys are different you can just use a map of tablename -> keyname (via a Dictionary is probably easiest) instead of the list:

// You'll want to whitelist the tables, so you are not
// trusting user input for the table name
var tables = new Dictionary<String, String>() { 
   {"Source", "SourceId" },
   ... 
};

foreach(var table in tables){
    if (Context.Request.UrlReferrer.ToString().ToLower().Contains(table.Key)){
        AccessControlRule(
           $"{table.Value}",
            "select {table.Value} from {table.Key} where IsDelete = 0", 
            AccessPermission.Allow
        );
    } else {
        AccessControlRule(
           $"{table.Value}", 
            "select {table.Value} from {table.Key} where IsDelete = 1 OR IsDelete = null",
            AccessPermission.Allow
        );
    }
}

Upvotes: 1

Related Questions