Optimize if sequence

2

I have the following structure and would like to optimize the if code, there are already several equal parts. Then I made a foreach. But the ExpandoObject type variable, I do not know how to handle it generically to get the value of the function.

If anyone can help me, I appreciate it. Here is the code above and my attempt:

//Antes
dynamic line = new ExpandoObject();
line.Filial = ""                
line.Cidade = "";
line.Cep = "";
line.Uf = "";
line.Cliente = "";              
line.Cnpj = "";

if (columnIndexes.Contains (Filial))
  line.Filial = GetValue(table, columnIndexes, Filial, i);

if (columnIndexes.Contains (Cidade))
  line.VendasQuantidade = GetValue(table, columnIndexes, Cidade, i);

if (columnIndexes.Contains (Cep))
  line.Cep = GetValue(table, columnIndexes, Cep, i);

if (columnIndexes.Contains (Uf))
  line.Uf = GetValue(table, columnIndexes, Uf, i);

if (columnIndexes.Contains (Cliente))
  line.Cliente = GetValue(table, columnIndexes, Cliente, i);

if (columnIndexes.Contains (Cnpj))
  line.Cnpj = GetValue(table, columnIndexes, Cnpj, i);
//Depois
var values = new List<string>() {Cidade, Cep, Uf, Cliente, Cnpj, Filial };  

foreach (var value in values)
{
  if (columnIndexes.ContainsValue(value))
  {
    lineToInsert[value] = GetMapValue(table, columnIndexes, value, i);(não funciona)
    lineToInsert[value.ToString] = GetMapValue(table, columnIndexes, value, i);(não funciona)
  }
}
    
asked by anonymous 05.04.2018 / 19:19

1 answer

1

If I understand correctly you want to check if a dynamic property of a ExpandoObject and set a value is that?

Adapting your code would look something like this:

dynamic line = new ExpandoObject();
        line.Filial = "";             
        line.Cidade = "";
        line.Cep = "";
        line.Uf = "";
        line.Cliente = "";              
        line.Cnpj = "";

        var fields = new List<string>() { "Cidade", "Cep", "Uf", "Cliente", "Cnpj", "Filial", "Algum" };
        // dicionário com as propriedades do ExpandoObject
        var dicLine = (IDictionary<string, object>)line;

        foreach(var f in fields)
        {
            if (dicLine.ContainsKey(f))
            {
                dicLine[f] = "teste";
            }
        }

        Console.WriteLine("line.Cep=" + line.Cep);

Just change the "test" value by the value you have in your code.

I've put a working example here: link

    
05.04.2018 / 20:00