How do I return an existing item in my enumerable via Contains?

Asked

Viewed 201 times

3

I have an enumerable, and I intend to query through a code per parameter. if the enumerable "Contains" Code, then it will return to me all items that are with this Code.

See I was trying to do it like this:

public IEnumerable<Relacao> Listar(int Codigo)
{
    return this.Context.Relacoes.Contains(codigo);
}

2 answers

5

The method Contains usually returns a boolean value (true or false) and not an enumeration.

You can use Where to create a filter over the Relacoes, and then use a condition for this filter, so that only the elements matching the condition are returned:

public IEnumerable<Relacao> Listar(int Codigo)
{
    // assumindo que uma "relação" possua a propriedade `Codigo`
    return this.Context.Relacoes
               .Where(rel => rel.Codigo == Codigo)
               .ToList();
}

The ToList at the end serves to obtain the database data at the time it is called. If you do not, the data will only be obtained in the future when the resulting enumeration is used. Without the ToList we would have a kind of lazy assessment.

If your goal is to have a lazy assessment, then you should remove the call from ToList, but in this case, I recommend changing the type of return also to IQueryable<Relacao>:

public IQueryable<Relacao> Listar(int Codigo)
{
    // assumindo que uma "relação" possua a propriedade `Codigo`
    return this.Context.Relacoes
               .Where(rel => rel.Codigo == Codigo);
}

2

Look, you can do the following:

public IEnumerable<Relacao> Listar(int codigo)
{
    return this.Context.Relacoes.Where(relacao => relacao.Codigo == codigo);
}

Case Codigo be the PK of Relacao and you want to return only one Relacao, do the following:

public Relacao Consultar(int codigo)
{
    return this.Context.Relacoes.Find(codigo);
}

Browser other questions tagged

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