I was creating my api to return cod_postal from any city to make some linked dropdown combos.
I realize in db some cod_postal are duplicated. So I try to remove it using GroupBy
Was getting some error until I found a sample working with a list. Sample
So I decide first create a List<dto>
and then perform the group by and that solve my duplicated problem as the code show.
The question is why I need that .ToList()
to join DTO and GroupBy steps?
public class cod_postalDTO
{
public int cod_postal_id { get; set; }
public string name { get; set; }
}
public class codPostalController : ApiController
{
private dbEntities db = new dbEntities ();
public List<cod_postalDTO> Getcod_postal(int city_id)
{
List<cod_postalDTO> l_cod_postal = db.cod_postal
.Where(c => c.city_id == city_id)
.Select(c => new cod_postalDTO
{
cod_postal_id = c.cod_postal_id,
name = c.name
})
.OrderBy(o => o.name)
.ToList() // <== why i need this line?
.GroupBy(c => c.name)
.Select(grp => grp.First())
.ToList();
return l_cod_postal;
}
If I don't include that middle .ToList
got the following error
El método 'First' sólo se puede usar como operación de consulta final. Considere la posibilidad de utilizar en su lugar el método 'FirstOrDefault' en esta instancia.
This is something like the 'First' method can only be use as final operation, consider use 'FirstOrDefault' instead.
But 'FirstOrDefault' doesn't work here neither