2
I have the following structure and would like to optimize the code of the if, there are already several equal parts. So I made a foreach. But the variable of type Expandoobject, I do not know how to deal with it in a generic way to receive the value of the function.
If someone can and knows how to help me, thank you. Follow below the previous code 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)
}
}
Thank you very much! That was exactly what was missing convert into dictionary. And this is because before he was an object and I was trying to work with him like a dictionary, right?
– Ana Carolina
Yes, in the background as it is a "typed" object, it cannot be like a class, so a
ExpandoObject
works with a dictionary, and to "take" its properties by name has to make the conversion to dictionary, only access by direct key does not work, apparently what was happening in this line:lineToInsert[value]
– Ricardo Pontual
I get it, thank you very much!
– Ana Carolina
Then don’t forget to accept the answer if it helped
– Ricardo Pontual