how to use Dictionary select . value concepts

Asked

Viewed 42 times

-1

what that select and . value means

var idProdutosDistintos = DictionaryVendas
  .Select(x => x.Value.Produto.Codigo)
  .Distinct()
  .Count();

sw.WriteLine("E - " + idProdutosDistintos);

1 answer

1

The object you are iterating is a Dictionary, which is an object of the type "key pair value", that is, an object that has a pair of data, a "key" which is the key, and a "value", which is the value itself.

The Select will interact on each item within your dictionary, as if it were a "loop", a foreach in each item of the dictionary, and the .Value will get the value.

That one Select can be replaced by something like:

foreach(var item in DictionaryVendas)
{
    var valor = item.Value;
}

But note that the Select greatly simplifies this, has other operations that are executed, all this using Linq.

Take this example:

var dic = new Dictionary<string, string>
{
    { "SouKey", "SouValue" },
    { "SouOutraKey", "SouValue" },
};

var qtdNaoDuplicados = dic
    .Select(x => x.Value)   // "Seleciono" cada valor dentro de cada item ("x") do dicionário
    .Distinct()  // Removo duplicados
    .Count();  // Conto os itens

var value = dic
  .Select(x => x.Value)
  .FirstOrDefault();

var key = dic
  .Select(x => x.Key)
  .FirstOrDefault();

Console.WriteLine("Value=" + value);
Console.WriteLine("Key=" + key);
Console.WriteLine("Quantide de valores não duplicados=" + qtdNaoDuplicados);

Here, I used the FirstOfDefault to take only the first element and demonstrate. The variable key will have the key, ie "Somekey", and the variable value will have the value, ie "Souvalue".

In your case, you will get the object that is in value, an object that has the property Produto.

For information purposes, the Distinct will remove the duplicates, the Count count how many elements you have.

You can see the example above working here: https://dotnetfiddle.net/0J3aKZ

Browser other questions tagged

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