Search code examples
linqtrim

how to remove a character at the end of a string in linq c#


I have the following LINQ query; I want to remove dot character if available at the end of string

var hatoList = (from L in db.vHatoList select L.HatoFullName.Trim('.')).ToList();

Solution

  • You're currently trying to perform the query in the database. We don't know what database technology you're using, so it's hard to know whether there's some way to make it actually happen in the database, but it's probably simplest to do in memory instead (given that it won't change how many records will be returned). The AsEnumerable() method is used to just change the compile-time type to IEnumerable<T> (instead of IQueryable<T>) forcing the rest of the query to be evaluated in .NET code instead of in the database:

    var hatoList = db.vHatoList 
                     .AsEnumerable()
                     .Select(entry => entry.HatoFullName.TrimEnd('.'))
                     .ToList();
    

    (I've also changed the call from Trim to TrimEnd to avoid it removing periods at the start of the string.)