List within a Dictionary

Asked

Viewed 104 times

-2

I have a method that receives a list of products, goes through this list and needs to return n lists of products separated by CNAE. I’m trying to come back as a dictionary, but then the doubt hits. If after adding an item to the list, during the first time, the second time I can add one more item to the list? I did it this way.

public IValidationResult GerarListas(List<TPV_PedidoItemInfo> Items, string TipoOS)
        {
            IValidationResult result = ValidationResult.Clear();
            try
            {
                using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { Timeout = new TimeSpan(0, 0, 10, 0) }))
                {

                    List<string> osTiposItens = new List<string>();

                    Dictionary<string, List<TPV_PedidoItemInfo>> listas = new Dictionary<string, List<TPV_PedidoItemInfo>>();
                    string key = "items";

                    foreach (TPV_PedidoItemInfo item in Items)
                    {
                        TAS_ProdutoInfo Produto = uow.TAS_ProdutoRepository.FindById(item.IDProduto);
                        if (Produto == null)
                        {
                            result.Add("Produto não encontrado!");
                            return result;
                        }

                        if (item.TipoItem != "I")
                        {
                            if (Produto.CNAE != null)
                            {
                                key += Produto.CNAE;
                                if (!listas.ContainsKey(key))
                                {
                                    listas.Add(key, new List<TPV_PedidoItemInfo> { item });
                                }
                                else {
                                    listas[key].Add(item);
                                }

                                if (!osTiposItens.Contains(key))
                                {
                                    osTiposItens.Add(key);
                                }
                            }
                        }
                    }

                    result.Object = new { listas};

                    scope.Complete();
                }
            }
            catch (Exception ex)
            {
                result.Add(ex.Message);
                result.Object = new { ex };
            }
            return result;
        }

1 answer

0


Apparently the mistake is on the line key += Produto.CNAE;. By doing the += within a foreach your key doesn’t have the value you expect.

Put the key creation (string key = "items";) within the foreach and should already have the expected result.

Another option would be to use only Produto.CNAE like Key, making key = Produto.CNAE.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.