Browse dictionaries with params in C #

366 Views Asked by At

I created a method that receives an unspecified amount of dictionaries parameters and scans the content of all of them but the same is not covered, it gives error in the first or second foreach, depending on what I fix. Consegundo'm not fix this problem. How could I make this work paraque.

I get the params dictionary and I want to go through the contents of each.

The code that I follow below:

public String getQuerySelectInner(String TABELA, params Dictionary<String, String> dictionaries)
{
    String sql = "SELECT ";

    foreach (Object dictionary in dictionaries)
    {
        foreach (var word in dictionary)
        {
            sql += word.Key + ",";
        }
    }

    sql = sql.Remove(sql.Length - 1);

    sql += " from " + TABELA + "  WHERE situacao = 'ATIVO' ";

    return sql;
}
1

There are 1 best solutions below

0
On

Your code doesn't even compile. Are you coding using notepad or an actual IDE?

Anyhow, if you add brackets for your params and change your outer foreach to a var rather than casting to an Object it compiles. Does that help to give you what you want?

    public String getQuerySelectInner(String TABELA, params Dictionary<String, String>[] dictionaries)
    {
        String sql = "SELECT ";

        foreach (var dictionary in dictionaries)
        {
            foreach (var word in dictionary)
            {
                sql += word.Key + ",";
            }
        }

        sql = sql.Remove(sql.Length - 1);

        sql += " from " + TABELA + "  WHERE situacao = 'ATIVO' ";

        return sql;
    }

To further improve things a bit you could use string.join instead of your inner loop: sql += string.Join(",", dictionary.Keys); which means you don't need to remove the extra comma after.