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

3

I have an enumerable, and I want to query through one code per parameter. if the enumerable "Contains" Code, then it will return me all items that have that Code.

See was trying to do so:

public IEnumerable<Relacao> Listar(int Codigo)
{
    return this.Context.Relacoes.Contains(codigo);
}
    
asked by anonymous 07.04.2015 / 13:47

2 answers

5

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

You can use Where to create a filter on Relacoes , and then use a condition for this filter, so that only elements that match 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 get the data from the database at the time it is called. If you do not do this, the data will only be obtained in the future when the resulting enumeration is used. Without ToList we would have a kind of lazy evaluation.

If your goal is to have a lazy assessment, then you should remove the ToList call, but in this case, I recommend that you change the return type 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);
}
    
07.04.2015 / 13:54
2

look, you can do the following:

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

If Codigo is the PK of Relacao and you want to return only a Relacao , do the following:

public Relacao Consultar(int codigo)
{
    return this.Context.Relacoes.Find(codigo);
}
    
07.04.2015 / 13:52