Error when selecting part of a string in the select of an entity using Entity Framework and Linq

Asked

Viewed 141 times

0

I need to assemble a Drop-down with part of the name of a project, which is very large in the database, goes up to 250 characters. For this I made a selector like this:

var lista = _projetoAppServ.ObterTodos("Descricao")
      .Select( a => new { 
                          ProjetoId= a.ProjetoId, 
                          Descricao = a.Descricao.Substring(0,50) 
                        })

However, there are projects with less than 50 characters, causing the error below: The index and length should refer to a location within the character string. Name of parameter: length

How to solve this problem?

  • I just found a solution: var list = _projectAppServ.Get all("Description"). Select( a => new { Projetoid= a.Projetoid, Descricao = ( (a.Descricao.Length > 50) ? a.Descricao.Substring(0,50) : a.Description ) });

1 answer

1


You can use Padright to fill in spaces.

var lista = _projetoAppServ.ObterTodos("Descricao")
      .Select( a => new { 
                          ProjetoId= a.ProjetoId, 
                          Descricao = a.Descricao.PadRight(50, ' ').Substring(0,50) 
                        })

Browser other questions tagged

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