How to pass a default parameter value within a foreach in C#?

Asked

Viewed 95 times

-1

Dear friends,

How could I pass a default parameter value within a foreach?

Example, inside my foreach I have an if that makes a certain comparison with an attribute of my class right?. But by default in c# when getting data from an attribute I need to pass which ID of the list position I want to receive such data (Ex: Employee lists[0].getCodigo(), Employee lists[1].getCodigo(), etc).

But my problem is just that I want to get all records with that attribute, in case I wouldn’t know the position of my ID exactly (EX:Employee Listings[N].getCodigo(), Employee lists[N].getCodigo() ).

I do not know if I was very clear, but is there any parameter 'standard' or something in the type that helps me in this case? thanks!

var ListaEmpregadosPorCodigo = ListaEmpregados.OrderBy(p => p.getCodigo());

foreach ( var codigo in ListaEmpregadosPorCodigo)
{
    int iCodigo = Convert.ToInt32(codigo.getCodigo());

    if (iCodigo == ListaEmpregados[].getCodigo())
    {
        //Código
    }
}
  • If p.getCodigo() returns the value of an attribute would not be better to create a property for such.

  • I don’t understand your need. You are scrolling through a list in your foreach. You want to pick up the current position of the loop?

1 answer

1

Well, you could use Linq to do this operation, plus lighter and cleaner code

try

var items = ListaEmpregados.Where(x => 
                   x.Any(z => z.getCodigo() ==  x.getCodigo())
            );

Browser other questions tagged

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