Make a foreach that does not repeat the same data

Asked

Viewed 118 times

1

I have this foreach, in a table with more than 5000 records. There are only 6 types of business unit. I would like that in the foreach and Ingl, when a type of UN appears, it loads and then does not repeat it, that is, it carries another different and so on, so that the result comes only 6 records. Down with my foreach.

foreach (var _idmotivo in monta_arvore)
            {
                _listaUnidade = db.Apresentacao
                                .Where(un => un.Codigo_Unidade_Negocio == _idmotivo.Codigo_Unidade_Negocio)
                                .Select(u => new MontaArvoreAcao
                                {
                                    Unidade_Negocio = u.Unidade_Negocio,
                                    Codigo_Unidade_Negocio = u.Codigo_Unidade_Negocio
                                }).ToList().OrderBy(o => o.Unidade_Negocio);
            }
  • I don’t understand which one you want to do it in. It’s in the tree or in the?

  • In the _list, as it brings me several names and would not like to see repeated. I used distinct and nothing.

1 answer

2


You can do it using the GroupBy.

_listaUnidade = db.Apresentacao
                                .Where(un => un.Codigo_Unidade_Negocio == _idmotivo.Codigo_Unidade_Negocio)
                                .Select(u => new MontaArvoreAcao
                                {
                                    Unidade_Negocio = u.Unidade_Negocio,
                                    Codigo_Unidade_Negocio = u.Codigo_Unidade_Negocio
                                })
                                .GroupBy(x=>x.Unidade_Negocio)
                                .Select(x=>x.First()
                                .ToList().OrderBy(o => o.Unidade_Negocio);
  • Let me explain. So just bring one and that’s not what I want, example. I have a total of 6 reasons. For each reason, I can have one or more UN and are also 6 UN in total. So there are Reasons that can bring 3 UN, others can bring 2, 4 or more or less. That’s what I need. However, a reason can have 300 Generics, so I just want it to show only 1(Generic) and the same for MIP, RX and etc....

  • My difficulty is in my Where. I will do another post thinking only about Where and how to bring each UN related to the past ID. Diego Zanardo’s answer is correct. I did it a little differently, but it’s the same thing posted by Diego Zanardo.

Browser other questions tagged

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